I have a table with id in database. I want to declare table variable with columns as much as id count in the id table(now its 16, but in future it will be more).
The columns name must be the id name.
I tried to use table_cursor, and dynamic query with creating table variable. And its worked, but in the future its called a lot of troubles. Does it possible to create table variable without dynamic query?
Advertisement
Answer
Try this
IF OBJECT_ID('dbo.TempTable') IS NOT NULL DROP TABLE TempTable CREATE TABLE TempTable (Id INT IDENTITY, Status_name varchar(30), [Count] INT ) INSERT INTO TempTable(Status_name,[Count]) SELECT 'in_Work' , 28 UNION ALL SELECT 'in_reserve' , 44 UNION ALL SELECT 'Planned_Stop' , 78 UNION ALL SELECT '_empty' , 55 UNION ALL SELECT 'Waiting' , 43 DECLARE @Sql nvarchar(max), @DynamicColumn nvarchar(max), @MaxDynamicColumn nvarchar(max) SELECT @DynamicColumn = STUFF((SELECT DISTINCT', '+QUOTENAME(CAST(Id AS VARCHAR(10))) FROM TempTable FOR XML PATH ('')),1,1,'') SELECT @MaxDynamicColumn = STUFF((SELECT DISTINCT', '+'MAX('+QUOTENAME(CAST(Id AS VARCHAR(10)))+') AS '+QUOTENAME('_'+CAST(Id AS VARCHAR(10))) FROM TempTable FOR XML PATH ('')),1,1,'') SET @Sql='SELECT '+ @MaxDynamicColumn+' FROM ( SELECT * FROM TempTable o )AS src PIVOT ( MAX([Count]) FOR [Id] IN ('+@DynamicColumn+') ) AS Pvt ' EXEC (@Sql) PRINT @Sql