我有一个Sql过程,它从表中选择记录,如果匹配insert到另一个表。它如下
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
任何人都可以提出改善此程序性能的提示
答案 0 :(得分:1)
如果没有看到基础表的结构,就无法提供帮助。尝试使用CTRL + L查看估计的执行计划。您可能想要评论CREATE PROCEDURE
内容,它会使计划更容易阅读。
通常情况下,创建一两个索引就是一个例子。
您可能会发现将C.CountryCode = @countryCode
从WHERE
子句移动到INNER 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