如何使用另一个表的行值作为列名称(动态)在SQL中创建新表?

时间:2014-06-25 18:59:44

标签: sql sql-server database sql-server-2008

如何使用另一个表的行值作为列名在SQL中创建新表?请注意原始表值是动态的。动态Pivot是唯一的选择吗?

例如,如果我的旧表看起来像:

players
-----------
Lebron James
Kobe Bryant
Dwayne Wade
Chris Bosh
James Harden

我希望新表看起来像:

Lebron James | Kobe Bryant | Dwayne Wade | Chris Bosh | James Harden

1 个答案:

答案 0 :(得分:0)

试试这个例子:

DROP TABLE #players 
CREATE TABLE #players (name VARCHAR(200))
INSERT INTO #players 
SELECT 'Lebron James'
UNION SELECT 'Kobe Bryant'
UNION SELECT 'Dwayne Wade'
UNION SELECT 'Chris Bosh'
UNION SELECT 'James Harden'


DECLARE @cmd VARCHAR(8000)
SET @cmd ='CREATE TABLE MyNewTable (id INT'
SELECT @cmd = @cmd + '
, ['+name+'] VARCHAR(255)'
FROM #players

SELECT @cmd = @cmd + ')'

PRINT @cmd
EXEC(@cmd)

EXEC('SELECT * FROM MyNewTable')