Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I Have this dynamic pivot query I need to put it's results in gridview
SQL
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX);
DECLARE @ColumnName AS NVARCHAR(MAX);

SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
       + QUOTENAME(id)
FROM (SELECT DISTINCT id FROM Projects.COMPUTER_PARTS) AS Courses;


SET @DynamicPivotQuery = 
N'SELECT *
  FROM (
select a.id,C.COMPUTER_NAME, A.PART_NAME
from Projects.PARTS_ON_COMPUTERS P
left join Projects.COMPUTERS C ON C.Id= P.COMPUTER
LEFT JOIN Projects.COMPUTER_PARTS A ON A.Id= P.PART
	   ) s
  PIVOT (
         MAX(PART_NAME) FOR id IN  (' + @ColumnName + ')
		) p
';
EXEC sp_executesql @DynamicPivotQuery;

please help
Posted
Updated 21-Dec-15 0:08am
v2
Comments
CHill60 21-Dec-15 6:51am    
So stick the query into a Stored Procedure and call that from your code behind and/or bind the GridView to the results ... or is that the bit you don't know how to do?
samerselo 21-Dec-15 7:03am    
could you please give me an example how to do that
this is my first time with pivot
CHill60 21-Dec-15 7:34am    
Pivot is irrelevant - it just produces results that you can use as would any other query. I've added a solution with some links to examples

1 solution

As per my comment - put this code into a Stored Procedure - MSDN reference[^]
and then populate the GridView from the results as per this reference[^]

This article[^] gives a worked example also
 
Share this answer
 
Comments
samerselo 21-Dec-15 7:50am    
thank you I'll see the links then back to you
samerselo 21-Dec-15 8:13am    
thank you a lot

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