這是用戶安全(我就稱呼它)的是我最終用來做我插入的版本。這實際上是爲導入數據集而設計的,如果沒有行級別的插入操作,在我看來會有些困難。當我跑這個時,大約需要2分鐘來插入50,000行。考慮到我的方式超過4列,一些列很大,我必須至少投一次(一些比其他更多),而且我必須使用LEFT或RIGHT進行各種切割以清除數據新表格。
Declare @Col1 varchar(50);
DECLARE @Col2 varchar (50);
DECLARE @col3 varchar (50);
DECLARE @col4 varchar (50);
DECLARE @T2ID int;
DECLARE @T3ID int;
DECLARE Cur1 CURSOR -- Create the cursor
LOCAL FAST_FORWARD
-- set the type of cursor. Note you could also use READ_ONLY and FORWARD_ONLY.
-- You would have to performance test to see if you benifit from one or the other
FOR
--select FROM base table Table1
SELECT
Col1, Col2, Col3, Col4
FROM
Table1
WHERE Col1 IS NOT NULL AND Col3 IS NOT NULL
-- If the main columns are null then they are skipped. This was
-- required for my data but not necessarily yours.
OPEN Cur1
FETCH NEXT FROM Cur1 INTO
@Col1, @Col2, @Col3, @Col4;
-- Assigns values to variables declared at the top
WHILE @@FETCH_STATUS = 0
BEGIN
-- Select from table 2
SELECT @T2ID = T2ID
-- where some data in the table is = to the stored data we are searching for
FROM Table2
WHERE @Col1 = [Col1]
IF @@rowcount = 0
BEGIN
INSERT INTO T2
(Col1
,Col2)
VALUES
(@Col1
,@Col2)
SET @T2ID = SCOPE_IDENTITY();
END;
-- Selects from Table3
SELECT @Col3 = Table3Col1
FROM Table3
IF @@rowcount = 0
-- If no rows are returned then proceed with insert
BEGIN
INSERT INTO Table3
(col3
,col4)
VALUES
-- Uses values assigned to the variables from the cursor select
(@col3
,@col4)
SET @T3ID = SCOPE_IDENTITY();
END;
-- Inserts the gathered row id's into the lookup table
INSERT INTO Table4
(Table2ID
,Table3ID)
VALUES (
@Table2ID
,@Table3ID)
FETCH NEXT FROM Cur1 INTO @Col1, @Col2, @col3, @col4;
END;
CLOSE Cur1;
DEALLOCATE Cur1;
如果有人有改進報價請做。我樂於接受建議。 另外,除非有人要我,否則我不會接受我的回答是正確的,因爲可能有更好的答案。
向我們展示了您執行您的要求的最佳途徑,從您實際卡住的內容開始。 –
根據你的解釋,光標不是必需的。唯一缺少的是你真實的表結構和數據類型。然後只能寫腳本。 – KumarHarsh
我實際上已經全力以赴。我知道如果我把它作爲答案發布,我將不會得到選票或其他任何東西。不要太在意他們。我只是想知道哪個是最好的地方。 – user3779413