如何使用另一个表的行值作为列名在SQL中创建新表?请注意原始表值是动态的。动态Pivot是唯一的选择吗?
例如,如果我的旧表看起来像:
players
-----------
Lebron James
Kobe Bryant
Dwayne Wade
Chris Bosh
James Harden
我希望新表看起来像:
Lebron James | Kobe Bryant | Dwayne Wade | Chris Bosh | James Harden
答案 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')