我需要一些幫助我的tsql,我有sql的知識,但主要只是查詢表和im找到tsql和循環相當困難完成。 我用我的IF語句命中了一個問題。 正如你所看到的,我已經編寫了循環並嘗試了一些調試,並且代碼目前爲止是正確的。幫助使用IF聲明
在其他部分 我需要檢查它是否是第一次通過使用@firstloop的循環,然後複製所有數據,其主要是我遇到問題的循環,並可以幫助獲取啓動點。
我正在使用遊標,但被告知它不會影響性能,因爲它沒有做太多的工作,我希望對問題有任何幫助。我也被告知某些部分是硬編碼的,如Production2應該是@Source_Database_Name。
declare @Source_Database_Name varchar(255) = 'Production2';
declare @Destination_Database_Name varchar(255) = 'c365online_script1';
declare @Company_Id int = 1 --declare a companyid
CREATE TABLE #CompanyID (ID bigint)
INSERT INTO #CompanyID(ID)
VALUES('15')
--FIRST CURSOR LOOP THROUGH THIS TABLE
CREATE TABLE #TableList (
processorder int,
tablename NVARCHAR(100)
)
INSERT INTO #TableList (processorder, tablename)
VALUES
(1, 'tProperty');
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 #CompanyID;
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 #TableList order by processorder;
open copyTableDataCursor
fetch next from copyTableDataCursor into @processorder, @tablename;
while @@FETCH_STATUS = 0
BEGIN
SET IDENTITY_INSERT [c365online_script1].[dbo].[tCompany] ON
-- Does the table have a companyID column? if statement checking for company id
IF EXISTS(SELECT * FROM Production2.INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME='CompanyID' and [email protected])
BEGIN
declare @debug varchar(max)
SET @debug = 'INSERT INTO ' + @Destination_Database_Name + '.dbo.' + @tablename + ' SELECT * FROM ' + @Source_Database_Name + '.dbo.' + @tablename + ' WHERE ' + @Source_Database_Name + '.dbo.' + @tablename + '.CompanyID = ' + CAST(@Company_Id as varchar(10))
print @debug
--EXEC(@debug)
--EXEC('INSERT INTO ' + @Destination_Database_Name + '.dbo.' + @tablename + ' SELECT * FROM ' + @Source_Database_Name + '.dbo.' + @tablename + ' WHERE ' + @Source_Database_Name + '.dbo.' + @tablename + '.CompanyID = ' + @Company_Id)
END
ELSE
-- if no check if this is the first time through company loop and copy all data- if @firstloop company exists look at information schema
BEGIN
Print 'No'
END
-- if yes then copy data based on companyID in cursor
--EXEC('INSERT INTO ' + @Destination_Database_Name + '.dbo.' + @tablename + ' SELECT * FROM ' + @Source_Database_Name + '.dbo.' + @tablename)
-- company logic
SET IDENTITY_INSERT [c365online_script1].[dbo].[tCompany] OFF
FETCH NEXT FROM copyTableDataCursor into @processorder,@tablename;
END
close copyTableDataCursor;
Deallocate copyTableDataCursor;
,你面對的是什麼問題,第一次。你還有什麼問題?有什麼錯誤? – user2919277
沒有錯誤我只是想檢查它的第一次使用@firstloop經歷循環的起點 – user1259076
爲什麼你使用遊標循環?您是否嘗試過純粹基於集合的解決方案? – Yuck