I have a scenario where I need help. I have a table from where I'm pulling Max data group by ID like below.
select ID, max(basic) as B, max(hra) as H
from #temp
group by ID
I have another table (only one column) where I have certain values. Number of rows or data of this table is dynamic. X and Y are just random data. There could be many rows with any varchar data.
select * from #dummy
Now I need rows of #dummy table as columns of #temp like below.
Earlier I was thinking of pivoting but it won't work as there is no relation between these two tables. Any help, TIA.
With a query like this you can create a "column list" with empty entries and create a dynamic SQL Statement. This you execute with EXEC
:
DECLARE @addColumns VARCHAR(MAX)=
(
SELECT ','''' AS ' + Name
FROM #dummy
FOR XML PATH('')
);
DECLARE @cmd VARCHAR(MAX)=
'SELECT ID, MAX(basic) as B, MAX(hra) as H ' + @addColumns + ' FROM #temp group by ID;'
EXEC (@cmd);
btw: The statement created will look like this:
SELECT ID, MAX(basic) as B, MAX(hra) as H ,'' AS x,'' AS y FROM #temp group by ID;
EDIT2: If you want to add these columns to some table permanently (to add data later) you could use the same approach:
DECLARE @addColumns VARCHAR(MAX)=
STUFF( (
SELECT ',' + Name + ' VARCHAR(100) NULL'
FROM @dummy
FOR XML PATH('')
),1,1,'');
DECLARE @cmd VARCHAR(MAX)=
'ALTER TABLE SomeTable ADD ' + @addColumns +';'
The statement would look like:
ALTER TABLE SomeTable ADD x VARCHAR(100) NULL,y VARCHAR(100) NULL;
this request is sick but i think cursor can do something with it.
DECLARE @SQLString varchar(100),@new_column varchar(10)
DECLARE dummy_cursor CURSOR FOR
SELECT Name FROM dummy
OPEN dummy_cursor
FETCH NEXT FROM dummy_cursor into @new_column
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQLString =
N'Alter TABLE temp ADD @new_column varchar(10)'
EXECUTE sp_executesql @SQLString;
FETCH NEXT FROM dummy_cursor
END
CLOSE dummy_cursor
DEALLOCATE dummy_cursor
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.