2

我正在尝试做这样的事情:

--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 做一些事情,但我试图避免这种情况。有什么好的方法可以做到这一点吗?

4

1 回答 1

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
于 2013-03-14T19:28:35.097 回答