Пожелание, это поможет.
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
Для этой цели вам понадобится динамический SQL. –
Буду признателен за любые предложения или код о том, как это реализовать. – sh4rk