开发者

Create table using rows from another table as columns

I have a table with the following structure :

TableNo1

Field1

row1

row2

row3

row4

row5

...

...

...

row n

Now I need to create a new table with the following schema:

TableNo2

Field1(row1 of Table1) Field2(row2 of Table1) Field3(row3 of table1) Fieldn(row 开发者_运维技巧n of table1)

I read about this but only thing i was able to find is the into clause which doesnt work.

Can anyone please help?


You can use dynamic SQL

DECLARE @TableNo1 TABLE(Field varchar(128),DataType varchar(128))
DECLARE @s nvarchar(max)='CREATE TABLE dbo.TableNo2('
INSERT INTO @TableNo1
VALUES
('Field1','nvarchar(max)'),
('Field2','int')

SELECT  @s+=T.Field+' '+T.DataType+',' FROM   @TableNo1 T
SET @s=LEFT(@s,LEN(@s)-1)+')'
EXECUTE(@s)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜