我基本上尝试在某些表的多个列上执行相同的过程。我有程序,以及访问每列的游标语句,但我不能将我的表作为变量传递给游标:
代码:
DECLARE @columnName varchar(200),
@Table1 TABLE(
[Code] [nvarchar](50) NOT NULL,
[Name] [nvarchar](255) NOT NULL,
[Value1] [nvarchar](50) NOT NULL,
[Value2] [nvarchar](50) NOT NULL,
[Value3] [nvarchar](50) NOT NULL
),
@Table2 TABLE(
[Code] [nvarchar](50) NOT NULL,
[Name] [nvarchar](255) NOT NULL,
[Value1] [nvarchar](50) NOT NULL
[Value2] [nvarchar](50) NOT NULL,
[Value3] [nvarchar](50) NOT NULL
)
INSERT @Table1 EXEC ProcedureThatAddsData;
INSERT @Table2 EXEC ProcedureThatAddsData;
DECLARE col_cursor CURSOR FOR
select c.name from sys.tables t inner join sys.columns c on t.object_id = c.object_id where t.name = 'MySpecificTable'
OPEN col_cursor
FETCH NEXT FROM col_cursor
INTO @columnName
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @columnName
--BEGIN BODY
DECLARE @sql nvarchar(4000)
set @sql = '
INSERT INTO MySavedDifferencesTable
select t1.Code, t1.Name, t1.'+ @columnName +' as OldValue, t2.'+ @columnName +' as NewValue
from '+@Table1+' t1
join '+@Table2+' t2
on t1.Code = t2.Code
and t1.Name = t2.Name
WHERE ISNULL(t1.' + @columnName +','') != ISNULL(t2.' + @columnName +','')
';
exec (@sql)
--end BODY
FETCH NEXT FROM col_cursor
INTO @columnName
END
CLOSE col_cursor;
DEALLOCATE col_cursor;
如何使此过程正常工作。游标中的列选择正在工作,因此@columnName
将遍历MySpecificTable
中存在的所有列,但我在游标中传递2个表变量时遇到问题(for循环?)。
编辑:
这是我尝试添加到光标的部分:
@Table1 TABLE(
[Code] [nvarchar](50) NOT NULL,
[Name] [nvarchar](255) NOT NULL,
[Value1] [nvarchar](50) NOT NULL,
[Value2] [nvarchar](50) NOT NULL,
[Value3] [nvarchar](50) NOT NULL
),
@Table2 TABLE(
[Code] [nvarchar](50) NOT NULL,
[Name] [nvarchar](255) NOT NULL,
[Value1] [nvarchar](50) NOT NULL
[Value2] [nvarchar](50) NOT NULL,
[Value3] [nvarchar](50) NOT NULL
)
INSERT @Table1 EXEC ProcedureThatAddsData;
INSERT @Table2 EXEC ProcedureThatAddsData;
声明临时表变量并在游标内插入数据,或者以某种方式在游标内部传递已经充满数据的临时表。
答案 0 :(得分:0)
我最终做的是创建一个临时表
-- check if temporary table already exists
-- if not create it
IF OBJECT_ID('tempdb..#MyTempTable') IS NULL
begin
--table with same columns as snapshot table to insert current data
--MyTempTable
CREATE TABLE #MyTempTable(
[Code] [nvarchar](50) NOT NULL,..
)
end
--remove old data if it exists from the temporary MyTempTable table
delete from #MyTempTable;
--insert the current data into the temporary MyTempTable table
INSERT #SSDEStudySpecific EXEC procThatinsertsData;
现在我更新了在光标内部执行的sql:
set @sql = '
INSERT INTO MySavedDifferencesTable
select t1.Code, t1.Name, t1.'+ @columnName +' as OldValue, t2.'+ @columnName +' as NewValue
from '+#MyTempTable1+' t1
join SomeSystemTable t2
on t1.Code = t2.Code
and t1.Name = t2.Name
WHERE ISNULL(t1.' + @columnName +','') != ISNULL(t2.' + @columnName +','')
';