如何使用动态SQL在游标中附加SQL语句?

时间:2013-01-24 00:39:27

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

我正在尝试执行以下脚本( SQL Server 2008 ),但是当我在底部执行最终PRINT(@sql)时,似乎始终缺少脚本的第一部分。我是否以某种方式覆盖了剧本的第一部分?

我认为问题在于在@sql中声明CURSOR变量。当我将声明移到OPEN @tableCursor以上时,我会收到不同的输出。在表格游标中设置@sql变量有什么意义?

OPEN @tableCursor
FETCH NEXT FROM @tableCursor INTO @constituentId, @internalName, @fieldName, @value
WHILE (@@fetch_status = 0)
BEGIN

SET @sql = ''
IF (@fieldName = 'MARKET_SECTOR_DES')
BEGIN
-- this is the section that is missing when I do the PRINT(@sql) below
SELECT @sql = @sql + '
    -- Update BloombergMarketSector
    UPDATE dbo.Constituent
    SET BloombergMarketSector = ''' + @value + ''',
        ModifiedDate = GETDATE()
    WHERE id = ' + @constituentId + '
    '
PRINT (@sql) -- this works
END

PRINT (@sql) -- this works - it seems the issue is happening with this SELECT statement
SELECT @sql = @sql + '              
    -- Update the Column                
    -- The Column Exists - update
    IF NOT EXISTS (
                SELECT TOP 1 *
                FROM dbo.ConstituentBloombergAttribute AS cba
                WHERE cba.ConstituentId = ' + @constituentId + ')
    BEGIN
        INSERT
        INTO dbo.ConstituentBloombergAttribute (ConstituentId, ModifiedBy, ModifiedDate, CreatedBy, CreatedDate)
        VALUES (' + @constituentId + ', ''admin'', GETDATE(), ''admin'', GETDATE())                     
    END

    UPDATE dbo.ConstituentBloombergAttribute
    SET ' + @internalName + ' = ''' + @value + ''',
        ModifiedDate = GETDATE()
    WHERE ConstituentId = ' + @constituentId + '
    '

PRINT @sql
FETCH NEXT FROM @tableCursor INTO @constituentId, @internalName, @fieldName, @value
END

1 个答案:

答案 0 :(得分:0)

你的一个变量是null,试试这个:

SELECT @sql = @sql + '
    -- Update BloombergMarketSector
    UPDATE dbo.Constituent
    SET BloombergMarketSector = ''' + isnull(@value,'V MISSING') + ''',
        ModifiedDate = GETDATE()
    WHERE id = ' + isnull(@constituentId,'C MISSING') + '
    '

可能是数据库设置:当SET CONCAT_NULL_YIELDS_NULL为ON时,将空值与字符串连接会产生NULL结果。例如,SELECT'abc'+ NULL产生NULL。当SET CONCAT_NULL_YIELDS_NULL为OFF时,将空值与字符串连接将产生字符串本身(空值被视为空字符串)。例如,SELECT'abc'+ NULL产生abc。