我对sys.Columns有一些查询结果:
DECLARE @queryRWordsSameType VARCHAR(500) ='[ItemCode],[ItemDesc],[ItemId],[ItemName]'
如何使每个逗号分隔的值如下:
DECLARE @queryRWordsSameType VARCHAR(500) ='CAST([ItemCode] AS NVARCHAR(100)) AS [ItemCode]
,CAST([ItemDesc] AS NVARCHAR(100)) AS [ItemDesc]
,CAST([ItemId] AS NVARCHAR(100)) AS [ItemId]
,CAST([ItemName] AS NVARCHAR(100)) AS [ItemName]'
答案 0 :(得分:0)
我想你是以逗号分隔列表的形式选择sql表的所有列,对吗?
我们可以使用COALESCE函数作为逗号分隔值。至于列,请参阅sys.columns和sys.tables定义。
您可以使用此代码段。
DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',', '') + '[' + c.name + ']'
FROM sys.tables t
INNER JOIN sys.columns c
ON c.object_id = t.object_id
WHERE t.name = '<Your Table>'
SELECT @listStr
答案 1 :(得分:0)
在这里(虽然这是直接从syscolumns构建整个字符串):
DECLARE @queryRWordsSameType VARCHAR(500) = ''
SELECT @queryRWordsSameType += CASE WHEN @queryRWordsSameType <> '' THEN ',' ELSE '' END + 'CAST([' + name + '] AS NVARCHAR(100)) AS [' + name + ']' + CHAR(13) + CHAR(10)
FROM syscolumns
WHERE id = object_id('YOUR_TABLE_NAME')
PRINT @queryRWordsSameType