SQL Server 2016输出逗号分隔的表名列表

时间:2017-10-17 20:02:42

标签: sql sql-server tsql sql-server-2016 coalesce

我有以下T-SQL查询(将在存储过程中):

DECLARE @columnNames nvarchar(MAX);

SELECT 
    @columnNames = COALESCE(@columnNames + ',','') + sC.name 
FROM 
    sys.columns sC
JOIN 
    sys.tables AS sT ON sT.object_id = sC.object_id
WHERE 
    sC.name NOT IN (SELECT name 
                    FROM sys.identity_columns 
                    WHERE is_identity = 1)
    AND sT.name = 'Audit' 
ORDER BY 
    sC.column_id 

INSERT INTO [B2017].[dbo].[Audit] (@columnNames) 
VALUES ('')

如果我这样跑:

DECLARE @columnNames nvarchar(MAX);

SELECT 
    @columnNames = COALESCE(@columnNames + ',','') + sC.name 
FROM 
    sys.columns sC
JOIN 
    sys.tables AS sT
ON 
    sT.object_id = sC.object_id
WHERE 
    sC.name NOT IN (SELECT name FROM sys.identity_columns WHERE is_identity = 1)
AND 
    sT.name = 'Audit' 
ORDER BY 
    sC.column_id 

它显示应该:

columnName1,columnName2,columnName3,etc...

但是,我想要做的是将(@columnNames)输出到INSERT INTO,以便我可以随时动态更改Audit表列名,而无需编辑存储过程

因此,以上面的示例列名称为例,我正在尝试这样做:

INSERT INTO [B2017].[dbo].[Audit] (columnName1, columnName2, columnName3,etc...) 
VALUES ('somevalue1,somevalue2,somevalue3,...')

当尝试上面的完整代码(包括INSERT INTO)时,我收到此错误:

  

Msg 207,Level 16,State 1,Line 51
  列名称“@columnNames”无效

3 个答案:

答案 0 :(得分:0)

您需要使用动态SQL:

declare @sql nvarchar(max);

set @sql = '
INSERT INTO [B2017].[dbo].[Audit] ([columnNames]) 
    VALUES ('''')
';

set @sql = replace(@sql, '[columnNames]', '@columnNames')

exec sp_executesql @sql;

话虽如此,这段代码仍然无效。您将一个值传递给values,但有多列。您需要调整值才能正确。

答案 1 :(得分:0)

您需要实现如下的动态查询:

.menu-trigger {
  background-color: #0000BB;
  color: #fff;
  cursor: pointer;
  display: block;
}

.header {
  position: fixed;
  background-color: #fff;
  padding-right: 40px;
}

a {
  text-decoration: none;
}

答案 2 :(得分:0)

我还找到了一种工作方法:

INSERT INTO 
    [B2017].[dbo].[Audit] OUTPUT (@columnNames)
VALUES 
    ('somevalue1,somevalue2,somevalue3,...')

这就像我需要它一样。