优化的存储过程

时间:2013-01-08 15:46:03

标签: sql-server stored-procedures sql-server-2008-r2

我正在使用SQL Server 2008 R2。我有这样的存储过程:

ALTER PROCEDURE [dbo].[GetZone]
    -- Add the parameters for the stored procedure here
@TheInsee int
AS
BEGIN
declare @Zone int

declare @CountA int
declare @CountB int
declare @CountC int
declare @CountD int
declare @CountN int
declare @CountP int
declare @CountN1 int
declare @CountN2 int
declare @CountN3 int
declare @CountN4 int
declare @CountN5 int
declare @CountN6 int

SELECT @CountA = COUNT(*) FROM LS_CLIENT_INSEE_A WHERE NO_INSEE = @TheInsee
SELECT @CountB = COUNT(*) FROM LS_CLIENT_INSEE_B WHERE NO_INSEE = @TheInsee
SELECT @CountC = COUNT(*) FROM LS_CLIENT_INSEE_C WHERE NO_INSEE = @TheInsee
SELECT @CountD = COUNT(*) FROM LS_CLIENT_INSEE_D WHERE NO_INSEE = @TheInsee
SELECT @CountN = COUNT(*) FROM LS_CLIENT_INSEE_N WHERE NO_INSEE = @TheInsee
SELECT @CountP = COUNT(*) FROM LS_CLIENT_INSEE_P WHERE NO_INSEE = @TheInsee

SELECT @CountN1 = COUNT(*) FROM LS_CLIENT_INSEE_N1 WHERE NO_INSEE = @TheInsee
SELECT @CountN2 = COUNT(*) FROM LS_CLIENT_INSEE_N2 WHERE NO_INSEE = @TheInsee
SELECT @CountN3 = COUNT(*) FROM LS_CLIENT_INSEE_N3 WHERE NO_INSEE = @TheInsee
SELECT @CountN4 = COUNT(*) FROM LS_CLIENT_INSEE_N4 WHERE NO_INSEE = @TheInsee
SELECT @CountN5 = COUNT(*) FROM LS_CLIENT_INSEE_N5 WHERE NO_INSEE = @TheInsee
SELECT @CountN6 = COUNT(*) FROM LS_CLIENT_INSEE_N6 WHERE NO_INSEE = @TheInsee

set @Zone = 
      CASE 
         WHEN @CountA >  0   THEN 1
         WHEN @CountB >  0   THEN 2
         WHEN @CountC >  0   THEN 3   
         WHEN @CountD >  0   THEN 4
         WHEN @CountN >  0   THEN 5
         WHEN @CountP >  0   THEN 6  
         WHEN @CountN1 >  0   THEN 7
         WHEN @CountN2 >  0   THEN 8
         WHEN @CountN3 >  0   THEN 9
         WHEN @CountN4 >  0   THEN 10
         WHEN @CountN5 >  0   THEN 11
         WHEN @CountN6 >  0   THEN 12   
         ELSE 1    
      END

RETURN @Zone  

END

它运行正常但是当每个表的数据非常大时,它会因为超时而挂出。我想知道我是否可以简化这个存储过程。

这个存储过程非常简单:我只提供一个输入@TheInsee,当它在内部找到时,它会搜索六个表。

请帮忙吗?

1 个答案:

答案 0 :(得分:0)

首先,由于您只检查每个表中是否存在至少一行,因此计算所有行是没有意义的。其次,如果您已在上一个表中找到行,则查询所有表是没有意义的。

我会做这样的事情:

set @Zone = case
    when exists (select * from dbo.LS_CLIENT_INSEE_A where NO_INSEE = @TheInsee) then 1
    when exists (select * from dbo.LS_CLIENT_INSEE_B where NO_INSEE = @TheInsee) then 2
    -- etc.
    else 1
    end