基本上我正在寻找一个临时表,其中列出了需要更新的某些表名,我将每个表名使用它来填充要更新的所有 ID 的另一个临时表。
我可以使用此结构选择需要更新的每个表中的数据,但似乎无法运行内部游标,因为它没有拾取临时表。
任何帮助都将不胜感激,因为在过去的几个小时里,这一直是我的疯子。
干杯,
DECLARE @table INT
DECLARE @prefix nvarchar(3)
DECLARE @TableName nvarchar(50)
DECLARE @TableIdName nvarchar(50)
DECLARE @getTable CURSOR
SET @getTable = CURSOR FOR
SELECT DISTINCT(id)
FROM @t
OPEN @getTable
FETCH NEXT
FROM @getTable INTO @table
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @TableName = name FROM @t WHERE id = @table
SET @TableIdName = @TableName + 'Id'
SELECT @prefix = prefix FROM @t WHERE name = @TableName
--PRINT @table
PRINT @TableName
--PRINT @TableIdName
--PRINT @prefix
DECLARE @temptable table(rid int, rTableName nvarchar(50), rprefix nvarchar(3), rpk nvarchar(50))
EXEC ('INSERT INTO ' + @temptable + ' SELECT ' + @TableIdName + ', ' + @TableName + ', ' + @prefix + @TableIdName + ' FROM ' + @TableName)
DECLARE @rTableName nvarchar(50)
DECLARE @rpk nvarchar(50)
DECLARE @rprefix nvarchar(3)
DECLARE @row INT
DECLARE @getRow CURSOR
SET @getRow = CURSOR FOR
SELECT DISTINCT(rid)
FROM @temptable
OPEN @getRow
FETCH NEXT
FROM @getRow INTO @row
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @row
SELECT @rTableName = rTableName FROM @temptable WHERE rid = @row
SELECT @rpk = rpk FROM @temptable WHERE rid = @row
SELECT @rprefix = rprefix FROM @temptable WHERE rid = @row
EXEC ('UPDATE ' + @rTableName + ' SET CoiRef = ' + @rprefix + '_' + @row + ' WHERE ' + @rpk + ' = ' + @row)
FETCH NEXT
FROM @getRow INTO @row
END
CLOSE @getRow
DEALLOCATE @getRow
FETCH NEXT
FROM @getTable INTO @table
END
CLOSE @getTable
DEALLOCATE @getTable
我也尝试了另一种解决方案,sp_executesql
但在那里得到了类似的错误,这是在第一个 EXEC 上使用下面的代码而不是 ..
DECLARE @sqlCommand nvarchar(500)
SET @sqlCommand = 'INSERT INTO @temptable SELECT TableIdName, TableName, prefix, TableIdName FROM' + @TableName
EXECUTE sp_executesql @sqlCommand, N'@temptable nvarchar(50) output', @temptable OUTPUT
再次,任何帮助将不胜感激..
谢谢..
格里