检查表是否具有companyID列

时间:2013-10-29 15:26:04

标签: sql sql-server tsql cursor ssms

使用SQl,如果使用if语句的CompanyID,我如何检查@DestinationDatabase中所有表的列?在下面代码的while循环中?。

我被告知游标有性能问题,但这是我上面的人选择采取的路线。

DECLARE @firstLoop BIT
SET @firstLoop = true
DECLARE @Counter INT  -- counting variable

----------- 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
            ELSE
              IF @firstLoop > =1 THEN

            -- 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 :(得分:1)

您可以在WHILE循环中添加它。我认为这是您正在寻找的解决方案。

IF (
    SELECT 1
    FROM sys.tables st
    INNER JOIN sys.columns sc
        ON st.object_id = sc.object_id
    WHERE st.NAME = @tablename
        AND sc.NAME = @company_id
    ) > 0
    BEGIN
        -- your logic here --
    END
ELSE
    -- other logic here --