我正在尝试执行以下脚本(SQL Server 2008PRINT(@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