我需要一种通用的方法来执行这种查询:
select t.column1+t.column2+t.column3+....+t.column25 from myTable t;
所以我正在寻找的是这样的:
select concat(*) from myTable t;
有没有办法做到这一点?
答案 0 :(得分:3)
DECLARE @Names VARCHAR(8000)
DECLARE @SQLQuery AS NVARCHAR(500)
SELECT @Names = COALESCE(@Names + ', ', '') + name
FROM sys.columns WHERE object_id = OBJECT_ID('tablename')
SET @SQLQuery = 'SELECT CONCAT(' + @Names + ') FROM tablename '
EXECUTE(@SQLQuery)
答案 1 :(得分:2)
试试这个:
DECLARE @TableName SYSNAME = 'dbo.MyTable'
SELECT STUFF
(
(
SELECT ', ' + [name]
FROM [sys].[columns]
WHERE [object_id] = OBJECT_ID(@TableName)
ORDER BY [column_id]
FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)')
,1
,1
,''
);
根据列的创建顺序连接列。对于宽表(包含许多列的表)来说没问题。