这是用户安全(我就称呼它)的是我最终用来做我插入的版本。这实际上是为导入数据集而设计的,如果没有行级别的插入操作,在我看来会有些困难。当我跑这个时,大约需要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