1

我有一个 Sql 过程,它从表中选择记录,如果它匹配插入到不同的表。如下

    CREATE PROCEDURE [dbo].[MarkCopyData] 
@copyDataOperationId int,
@countryCode nvarchar(50),
@batchCount int,@batchId int,@jobId int
    AS
    BEGIN
DECLARE @TableObjectId AS Int;
SET @TableObjectId = OBJECT_ID('Table1');
INSERT INTO  
    Table2(
            TableObjectId, 
            SourcePrimaryKey, 
            DestinationCopyOperationId, 
            IsModifiedAftertCopied,IsDeleted,BatchId,JobId)

    SELECT TOP (@batchCount) @TableObjectId, tbl1.pkid, @copyDataOperationId,      0,0,@batchId,@jobId
    FROM [dbo].[Table1] AS tbl1
    Inner join [dbo].[Country] AS C on C.CountryId =  tbl1.fkid
    LEFT OUTER JOIN Table2 tbl2 on (tbl2 .SourcePrimaryKey = tbl1.pkid and tbl2 .TableObjectId = @TableObjectId)
    WHERE C.CountryCode = @countryCode AND tbl2.DestinationCopyOperationId IS NULL
    SELECT @@ROWCOUNT
    END
    GO

任何人都可以请提出提示以提高此过程的性能

4

1 回答 1

1

如果没有看到基础表的结构,就不可能提供帮助。尝试使用 CTRL+L 查看估计的执行计划。您可能想要注释掉这些CREATE PROCEDURE内容,这将使计划更易于阅读。

通常,这将是创建一个或两个索引的情况。

您可能会发现将C.CountryCode = @countryCodefromWHERE子句移到 theINNER JOIN可能会有所帮助。通常,您希望在开始执行外部联接之前过滤结果集。

SELECT TOP (@batchCount) @TableObjectId, tbl1.pkid, @copyDataOperationId,0,0,@batchId,@jobId
FROM [dbo].[Table1] AS tbl1
Inner join [dbo].[Country] AS C on C.CountryId =  tbl1.fkid AND C.CountryCode = @countryCode
LEFT OUTER JOIN Table2 tbl2 on (tbl2 .SourcePrimaryKey = tbl1.pkid and tbl2 .TableObjectId = @TableObjectId)
WHERE tbl2.DestinationCopyOperationId IS NULL
于 2013-02-14T07:42:53.693 回答