Click here to Skip to main content
16,016,168 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI ,

I'm using StoredProcedure to display result in myu Grid...

My result set is look like this

Doc_Id	CL_Id	CL_Desc	       Rev_No	dwg_status_code	EMP_Name
146508	15	C-BF-FT-02 R2	0	DWS000002	NULL
146508	15	C-BF-FT-02 R2	0	DWS000003	NULL
146508	15	C-BF-FT-02 R2	0	DWS000025	NULL
146508	16	C-BF-FT-03 R2	0	DWS000002	KARTHIKEYAN K
146508	16	C-BF-FT-03 R2	0	DWS000003	KARTHIKEYAN K
146508	16	C-BF-FT-03 R2	0	DWS000025	KARTHIKEYAN K


But i want to display in my grid it self like this

Doc_Id	CL_Id	CL_Desc	       Rev_No	DWS000002    DWS000003      DWS000025	
146508	15	C-BF-FT-02 R2	0	NULL	     NULL           NULL
146508	16	C-BF-FT-03 R2	0	KARTHIKEYAN   KARTHIKEYAN    KARTHIKEYAN 


like PIVOT in SQL , But in Coding side how to do this logic. Can anyone give me some suggestion regarding this...
Posted
Comments
Maciej Los 13-May-13 9:35am    
How many dwg_status_codes do you have?

 
Share this answer
 
Comments
Maciej Los 13-May-13 13:02pm    
Interesting articles ;)
+5
Mehdi Gholam 13-May-13 13:26pm    
Cheers Maciej!
Try this:

SQL
IF NOT OBJECT_ID(N'#tmp') IS NULL DROP TABLE #tmp


CREATE TABLE #tmp(Doc_Id INT, CL_Id INT, CL_Desc NVARCHAR(30), Rev_No INT, dwg_status_code NVARCHAR(30), EMP_Name NVARCHAR(30))

INSERT INTO #tmp (Doc_Id, CL_Id, CL_Desc, Rev_No, dwg_status_code, EMP_Name)
VALUES(146508, 15, 'C-BF-FT-02 R2',	0,	'DWS000002', NULL)
INSERT INTO #tmp (Doc_Id, CL_Id, CL_Desc, Rev_No, dwg_status_code, EMP_Name)
VALUES(146508, 15, 'C-BF-FT-02 R2',	0,	'DWS000003', NULL)
INSERT INTO #tmp (Doc_Id, CL_Id, CL_Desc, Rev_No, dwg_status_code, EMP_Name)
VALUES(146508, 15, 'C-BF-FT-02 R2',	0,	'DWS000025', NULL)
INSERT INTO #tmp (Doc_Id, CL_Id, CL_Desc, Rev_No, dwg_status_code, EMP_Name)
VALUES(146508, 16, 'C-BF-FT-03 R2',	0,	'DWS000002', 'KARTHIKEYAN K')
INSERT INTO #tmp (Doc_Id, CL_Id, CL_Desc, Rev_No, dwg_status_code, EMP_Name)
VALUES(146508, 16, 'C-BF-FT-03 R2',	0,	'DWS000003', 'KARTHIKEYAN K')
INSERT INTO #tmp (Doc_Id, CL_Id, CL_Desc, Rev_No, dwg_status_code, EMP_Name)
VALUES(146508, 16, 'C-BF-FT-03 R2',	0,	'DWS000025', 'KARTHIKEYAN K')

--SELECT *
--FROM #tmp

DECLARE @cols NVARCHAR(300)
DECLARE @dt NVARCHAR(2000)
DECLARE @pt NVARCHAR(MAX)

SET @cols = STUFF((SELECT DISTINCT '],[' + dwg_status_code
					FROM #tmp
					ORDER BY '],[' + dwg_status_code
			FOR XML PATH('')),1,2,'') + ']'

SET @dt = N'SELECT * FROM #tmp'

SET @pt = N'SELECT Doc_Id, CL_Id, CL_Desc, Rev_No, ' + @cols + ' ' +
		'FROM ( ' + @dt + ') AS DT ' + 
		'PIVOT(MIN([EMP_Name]) FOR [dwg_status_code] IN(' + @cols + ')) AS PT'

EXEC(@pt)

DROP TABLE #tmp
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900