使用存储过程执行动态查询结果

时间:2016-06-28 11:55:11

标签: sql sql-server tsql

以下查询将返回60行,如何在一次运行中使用存储过程执行语句。

SELECT 'UPDATE TEMP1
SET ' + COLUMN_NAME + '= 0' + ' WHERE '+COLUMN_NAME+ ' IS NULL'
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'TEMP1' AND DATA_TYPE = 'FLOAT' 
AND COLUMN_NAME NOT IN('Sales','Net_Margin');

3 个答案:

答案 0 :(得分:1)

尝试在您的查询或GO关键字中添加分号,并执行以下操作

 declare @sql nvarchar(max)
    set @sql =
    (SELECT 'UPDATE TEMP1
      SET ' + COLUMN_NAME + '= 0' + ' WHERE '+COLUMN_NAME+ ' IS NULL'
     FROM INFORMATION_SCHEMA.COLUMNS 
     WHERE TABLE_NAME = 'TEMP1' AND DATA_TYPE = 'FLOAT' 
      AND COLUMN_NAME NOT IN('Sales','Net_Margin');)

exec(@Sql)
print @sql

答案 1 :(得分:1)

这是一种方法:

DECLARE @Sql nvarchar(max) = ''

SELECT @Sql = @Sql + 'UPDATE TEMP1
SET ' + COLUMN_NAME + '= 0' + ' 
WHERE '+COLUMN_NAME+ ' IS NULL;
'
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'TEMP1' AND DATA_TYPE = 'FLOAT' 
AND COLUMN_NAME NOT IN('Sales','Net_Margin');

PRINT @Sql -- remark this row once you check the sql and unremark the next one to execute

--EXEC(@Sql)

答案 2 :(得分:1)

首先创建SP:

CREATE PROCEDURE SPName
    @table_name sysname,
    @data_type sysname
AS
BEGIN
    DECLARE @sql nvarchar(max)

    SELECT @sql = @sql + 'UPDATE TEMP1 SET ' + COLUMN_NAME + '= 0' + ' WHERE '+COLUMN_NAME+ ' IS NULL;'
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_NAME = @table_name AND DATA_TYPE = @data_type
    AND COLUMN_NAME NOT IN('Sales','Net_Margin')

    EXEC sp_execute @sql

END

然后执行:

EXEC SPName 'TEMP1', 'FLOAT'