我希望根据以下示例表,有人对以下内容提出快速建议/解决方案:
|Field1 |Field2 |Field3 |Field4 |
|-------|-------|-------|-------|
| 1 | 0 | 0 | 1 |
我希望能够构建一个查询来返回列名,其值(基于单个记录)= 1.这样,不依赖于游标或临时表。
即。我想要以下输出:
Field1
Field4
我一直在尝试对sys.columns
(和sys.tables
)进行各种联接,但到目前为止还没什么用。
答案 0 :(得分:6)
您也可以使用Cross apply
SELECT Cname
FROM Tablename
CROSS apply (VALUES('Field1',Field1),
('Field2',Field2),
('Field3',Field3),
('Field4',Field4)) ca (cname, data)
WHERE data = 1
动态使用此功能。
CREATE TABLE test
(
Field1 INT,
Field2 INT,
Field3 INT,
Field4 INT
)
INSERT INTO test
VALUES ( 1,0,0,1 )
DECLARE @collist VARCHAR(max)='',
@sql NVARCHAR(max)
SELECT @collist += '(''' + COLUMN_NAME + ''',' + COLUMN_NAME + '),'
FROM INFORMATION_SCHEMA.columns
WHERE TABLE_NAME = 'test'
AND COLUMN_NAME LIKE 'Field%'
AND TABLE_SCHEMA = 'dbo'
SELECT @collist = LEFT(@collist, Len(@collist) - 1)
SET @sql ='
SELECT Cname
FROM test
CROSS apply (VALUES' + @collist
+ ') ca (cname, data)
WHERE data = 1 '
EXEC Sp_executesql
@sql
答案 1 :(得分:3)
您可以使用union all
执行此操作,例如:
select 'Field1' from table t where Field1 = 1 union all
select 'Field2' from table t where Field2 = 1 union all
select 'Field3' from table t where Field3 = 1 union all
select 'Field4' from table t where Field4 = 1;