0

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

我认为问题在于@sqlCURSOR. 当我将声明移到上方时,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
4

1 回答 1

0

您的变量之一为空,试试这个:

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。

于 2013-01-24T00:59:49.703 回答