2013-10-29 27 views
0

使用SQl如果他們有一個使用if語句的CompanyID,我將如何檢查@DestinationDatabase中所有表的列?在下面的代碼的while循環內?檢查表是否有companyID列

我被告知遊標有性能問題,但這是我上面有人選擇採取的路線。

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 
[email protected]_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

您沒有發佈您的代碼。 – dugas

回答

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 -- 
+0

感謝任何想法如何檢查這是否是第一次循環運行 – madzcoding

+0

@madzcoding您可以在我的語句中使用print語句,並帶有可變計數器。 –

+0

@madzcoding還是你打算修改基於第一次執行的程序流? –