我正在尝试做这样的事情:
--This table has a list of columns I need from #testTableTwo
CREATE TABLE #testTableOne
(
id nvarchar(250)
)
--This column has the values I need. I just don't know which columns I want.
CREATE TABLE #testTableTwo
(
one INT,
two INT,
three INT,
four int
)
INSERT INTO #testTableOne VALUES ('one'),('two'),('three')
INSERT INTO #testTableTwo VALUES (1,2,3,4)
SELECT (SELECT * FROM #testTableOne) FROM #testTableTwo
所以我想要的是:
SELECT ONE, TWO, THREE FROM #testTableTwo
这可能吗?我知道我可以制作一个nvarchar并用COALESCE做一些事情,但我试图避免这种情况。有没有好办法呢?
答案 0 :(得分:2)
你必须像这样使用动态SQL。
-- First construct the fields list
DECLARE @fields varchar(500)
SET @fields = STUFF((SELECT ', ' + #testTableOne.id
FROM #testTableOne
FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)')
, 1, 2, '')
-- Next construct the actual SQL statement
DECLARE @sql nvarchar(max)
SET @sql = 'SELECT '+@fields+' FROM #testTableTwo'
-- And last but not least run it.
EXEC sp_executesql @sql