替换序列

时间:2018-04-20 15:12:18

标签: sql sql-server database query-string

我有一个包含大约17k个唯一行的表,我需要按顺序运行这些语句集

  • 使用MASTERTABLE数据INSERT INTO TABLE1(MASTERTABLE有6列)
  • 来自TABLE1的新插入行的列ID(主键)的SELECT值
  • 使用存储过程
  • 更新TABLE2中的ID值

我试过了:

  • while循环:大约需要3个小时才能完成执行
  • cursor:隔夜执行后取消查询
  • 根据我的理解,我不能使用JOIN,因为我需要按顺序执行语句

2 个答案:

答案 0 :(得分:1)

问题不够详细。一般的想法我想用这样的东西

-- create a output table to hold new id, and key columns to join later
DECLARE @OutputTbl TABLE (ID INT, key_Columns in MASTERTABLE)

INSERT INTO TABLE1
OUTPUT INSERTED.ID, MASTERTABLE.key_columns INTO @OutputTbl 
SELECT *
FROM MASTERTABLE 

UPDATE T2
SET ID = o.ID
FROM TABLE2 t2
INNER JOIN OutputTbl o
  ON t2.key_column = o.key_column 

答案 1 :(得分:0)

也许您可以考虑在TRIGGERTABLE1TABLE2调用存储过程,然后您可以根据需要调用INSERT。一个接一个地或一块一块地..

DROP TRIGGER TR_UPD_TABLE2 
GO

CREATE TRIGGER TR_UPD_TABLE2 ON TABLE1 AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @columnID INT = NULL 

    IF (SELECT COUNT(*) FROM INSERTED)=1 BEGIN
        -- SINGLE INSERT
        SET @columnID = (SELECT columnID FROM INSERTED)

        EXEC TableTwoUpdateProcedure @columnID

    END ELSE BEGIN
        -- MASSIVE INSERT (IF NEEDED)
        SET @columnID = 0

        WHILE @columnID IS NOT NULL  BEGIN
            SET @columnID = (SELECT MIN(columnID) FROM INSERTED WHERE columnID > @columnID)

            IF @columnID IS NOT NULL BEGIN
                EXEC TableTwoUpdateProcedure @columnID
            END
        END

    END 
END