我试图执行下面的脚本(SQL Server 2008),但似乎脚本的第一部分始终缺失,当我在底部执行最后的PRINT(@sql)
时。我是否以某种方式覆盖脚本的第一部分?如何使用动态SQL在游标内附加SQL语句?
我认为问题是在CURSOR
内声明@sql
变量。当我移动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
您是否尝试过使用'SET'? –
@AbeMiessler我真的做了,我注意到了同样的事情。尽管如此,我会再试一次。 –
你确定'@fieldName ='MARKET_SECTOR_DES''? – Hogan