我正在创建一个查询来创建一个在SQL中有两个元素的表
SELECT [att1]
,[att2]
,[att3]
,[att4]
,[att5]
,[att6]
,[att7]
,[att8]
,[att9]
,[att10]
,att11 = att1,
att12 = att2,
att13 = att3,
att14 = att4,
att15 = att5,
att16 = att6,
att17 = att7,
att18 = att8,
att19 = att9,
att20 = att10
INTO Table_20
FROM Table_10;
什么是使这种动态变为动态的最佳方法,如果我有一个30 atts
的表,请创建一个30 * 2
个整数的表(大小加倍)?
答案 0 :(得分:2)
DECLARE
@table NVARCHAR(512) = N'dbo.Table_10';
@sql NVARCHAR(MAX) = N'',
@c INT;
SELECT @sql += N',' + name
FROM sys.columns
WHERE [object_id] = OBJECT_ID(@table)
AND name LIKE 'att%';
SELECT @c = @@ROWCOUNT;
SELECT @sql += N',att' + CONVERT(VARCHAR(12),
@c + CONVERT(INT, REPLACE(name, 'att', '')))
+ ' = ' + name
FROM sys.columns
WHERE [object_id] = OBJECT_ID(@table)
AND name LIKE 'att%';
SELECT @sql = N'SELECT ' + STUFF(@sql, 1, 1, '')
+ ' INTO dbo.Table_20 FROM ' + @table + ';';
PRINT @sql;
-- EXEC sp_executesql @sql;