根据任何表中的值选择列(列数是可变的)SQL

时间:2016-03-07 11:41:03

标签: sql sql-server-2008 dynamic-sql

我有一张桌子:

Table 1

我想只显示至少有一个值低于50的列:

Table 2

我需要一个执行此操作的存储过程。诀窍是我想在多个表上使用它,但列数可能因表而异。

可以这样做吗?

1 个答案:

答案 0 :(得分:0)

希望这会有所帮助。

SET NOCOUNT  ON 

DECLARE 
    @tablename VARCHAR(50) = 'Table1',
    @valuetocompare INT = 50,
    @otherfields VARCHAR(100) = 'Date, Hour,';

DECLARE @t AS TABLE (cname VARCHAR(10), cvalue INT)
DECLARE @sql NVARCHAR(1000);
DECLARE @cname VARCHAR(128);
DECLARE c CURSOR  
FOR
    SELECT NAME
    FROM   sys.[columns] AS c
    WHERE  c.[object_id] = OBJECT_ID(@tablename)
;

OPEN c;
FETCH NEXT  FROM c INTO @cname;

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sql =  'select ''' + @cname  + ''', ' + @cname + ' from '  + @tablename;

    INSERT INTO @t
      (
        cname,
        cvalue
      )
    EXECUTE (@sql);

    FETCH NEXT FROM c  INTO @cname;
END

CLOSE c;
DEALLOCATE c;

DECLARE @cnames VARCHAR(100) = '';
WITH dcnames AS (
         SELECT DISTINCT cname
         FROM   @t
         WHERE  cvalue < @valuetocompare
     )
SELECT @cnames = @cnames + cname +  ','
FROM   dcnames;

IF @cnames =  ''
    PRINT 'No column value is less than ' + CAST(@valuetocompare AS VARCHAR);
ELSE
BEGIN
      SET @sql =  'select ' + @otherfields  + LEFT(@cnames, LEN(@cnames) - 1)  + ' from ' + @tablename;
      EXECUTE (@sql);
END