使用带有SQL游标的while循环?

时间:2013-10-29 11:15:00

标签: sql tsql if-statement while-loop ssms

我正在创建一个sql脚本,我有2个游标来循环数据表游标和公司游标。 我有问题将公司光标放在一起使用while循环将数据复制到模式中 我需要使用If Statement

回答以下问题

该表是否有companyID列?检查公司ID的if语句 如果是,则根据游标中的companyID复制数据

我宣布了@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;

1 个答案:

答案 0 :(得分:0)

我建议你用while循环替换CURSORS。

SQL Server中的CURSORS成本表现非常糟糕,而是用临时表替换它们,而While循环肯定会提高性能,并且您将不得不编写更简单的编码类型。

有关SQL Server的文章,请查看以下链接 SQL Server real time articles