转换动态查询以执行查询串

时间:2014-08-06 12:35:03

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

您好我无法使用以下代码编写动态查询:

SELECT 'UPDATE ClientReportCancelOrder SET [' + COLUMN_NAME + '] = NULL 
WHERE [' + COLUMN_NAME + '] = '''''
FROM INFORMATION_SCHEMA.columns
WHERE DATA_TYPE IN ('char','nchar','varchar','nvarchar') and TABLE_NAME='ClientReportCancelOrder'

产生以下结果:

UPDATE ClientReportCancelOrder SET [RecordType] = NULL   WHERE [RecordType] = ''
UPDATE ClientReportCancelOrder SET [OrderEventTypeCode] = NULL   WHERE [OrderEventTypeCode] = ''
UPDATE ClientReportCancelOrder SET [ActionTypeCode] = NULL   WHERE [ActionTypeCode] = ''
etc.....

我需要在SQL proc中执行一堆结果查询。

请帮帮我。 感谢

1 个答案:

答案 0 :(得分:0)

希望这有帮助。

DECLARE @qry NVARCHAR(MAX)
SELECT  @qry = 
    COALESCE( @qry + ';', '') +
    'UPDATE ClientReportCancelOrder SET [' + COLUMN_NAME + '] = NULL 
    WHERE [' + COLUMN_NAME + '] = ''''' 
FROM INFORMATION_SCHEMA.columns
WHERE DATA_TYPE IN ('char','nchar','varchar','nvarchar') and TABLE_NAME='ClientReportCancelOrder'

EXECUTE sp_executesql @qry