SQL Server:使用条件获取表的列名

时间:2017-02-14 05:24:48

标签: sql sql-server

我这里有一个示例表 - 我希望获得值为1的所有列。有可能吗?

enter image description here

1 个答案:

答案 0 :(得分:1)

绝对有可能,但过程很漫长,我正在使用loop检查每一栏的内容。 通过从exists检索列名来获取数据sys.columns。如果它在任何条件下对您有所帮助,请试试这个:

这里我只检查每列的值为

CREATE TABLE testing(val1 INT, val2 INT, val3 INT)
INSERT INTO testing VALUES
(1, 0, 1),(1, 0, 1),(1, 1, 1)

Table: testing
val1    val2    val3
1       0       1
1       0       1
1       1       1

DECLARE @sql NVARCHAR(500), @list VARCHAR(500)
DECLARE @num INT=1, @col_name VARCHAR(100) = NULL, @cnt INT

WHILE(@num<=3)
BEGIN
SELECT @col_name = name FROM sys.columns 
          WHERE object_id = OBJECT_ID('testing') and column_id = @num
SET @cnt = 0
SET @sql = '
IF NOT EXISTS(SELECT 1 FROM testing WHERE ' + @col_name + ' = 0) SET @cnt = 1'

EXEC sp_executesql @sql, N'@cnt INT OUT', @cnt OUT

IF @cnt = 1
    SET @list = COALESCE(@list + ',', '') + @col_name

SET @num = @num+1
END

SET @sql = '
SELECT ' + @list + ' FROM testing'
EXEC(@sql)

OUTPUT:

val1    val3
1       1
1       1
1       1