我正在创建一个 sql 脚本,我有 2 个游标来循环数据一个表游标和一个公司游标。我在使用 while 循环将公司光标放在一起以将数据复制到架构中时遇到问题我需要使用 If 语句回答以下问题
该表是否有 companyID 列?if 语句检查公司 ID,如果是,则根据光标中的公司 ID 复制数据
我声明了一个@firstLoop
这是我的光标特定代码
DECLARE @firstLoop BIT
SET @firstLoop = true
----------- Cursor specific code starts here ------------
-- company cursor
declare copyCompanyDataCursor CURSOR fast_forward FOR
SELECT ID from #CompanyIDs;
open copyCompanyDataCursor
fetch next from copyCompanyDataCursor into @Company_Id;
WHILE @@FETCH_STATUS = 0
BEGIN
declare @processorder int;
declare @tablename varchar(500);
-- table cursor
declare copyTableDataCursor CURSOR fast_forward FOR
SELECT processorder,tablename from #TableList4 order by processorder;
open copyTableDataCursor
fetch next from copyTableDataCursor into @processorder, @tablename;
while @@FETCH_STATUS = 0
BEGIN
SET IDENTITY_INSERT [c365online_script1.dbo.tCompany] OFF
-- Does the table have a companyID column? if statement checking for company id
-- if yes then copy data based on companyID in cursor
-- if no check if this is the first time through company loop and copy all data
-- if @firstloop company exists look at information schema
-- insert into c365online_script1.dbo.tCompany(selec
EXEC('INSERT ' + @Destination_Database_Name + '.dbo.' + @tablename + ' SELECT * FROM ' + @Source_Database_Name + '.dbo.' + @tablename + ')')
-- company logic
SET IDENTITY_INSERT [c365online_script1.dbo.tCompany] ON
FETCH NEXT FROM copyTableDataCursor into @processorder,@tablename;
END
close copyTableDataCursor;
Deallocate copyTableDataCursor;
--INSERT INTO c365online_script1.dbo.tCompany
--SELECT *
--FROM production2.tCompany
--WHERE ISNULL(CompanyID, 0) = 0 -- copy all data where id is equal to zero
--@Destination_Database_Name
--
--EXEC(INSERT + @Destination_Database_Name + '.dbo.' + @tablename + ' SELECT * FROM ' + @Source_Database_Name + '.dbo.' + @tablename + ' WHERE ' + @Source_Database_Name + '.dbo.' + @tablename + '.CompanyID = ' + @Company_Id + ')'
SET @firstLoop = false;
FETCH NEXT FROM copyCompanyDataCursor into @Company_Id;
END
CLOSE copyCompanyDataCursor;
DEALLOCATE copyCompanyDataCursor;