SQL CASE SELECT返回char

时间:2011-10-19 11:06:54

标签: sql

我有6个表:LS_CLIENT_INSEE_A,B,C等。每个表只包含1个字段:INSEE。

我只是想知道我的输入是否存在于其中一个表中,并从表名(A,B,C等)返回相应的字母。

还有另一个原因要重写:

@TheInsee int
AS
BEGIN
declare @Zone char(1)

declare @CountA int
declare @CountB int
declare @CountC int
declare @CountD int
declare @CountF int
declare @CountP 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 @CountF = COUNT(*) FROM LS_CLIENT_INSEE_F WHERE NO_INSEE = @TheInsee
SELECT @CountP = COUNT(*) FROM LS_CLIENT_INSEE_P WHERE NO_INSEE = @TheInsee

set @Zone = 
      CASE 
         WHEN @CountA >  0   THEN 'A'
         WHEN @CountB >  0   THEN 'B'
         WHEN @CountC >  0   THEN 'C'   
         WHEN @CountD >  0   THEN 'D' 
         WHEN @CountF >  0   THEN 'F' 
         WHEN @CountP >  0   THEN 'P'         
      END  

END

以上查询是实现此目标的最佳方式吗?

提前谢谢你, 甜菊

2 个答案:

答案 0 :(得分:2)

这应该通过在发现命中时停止选择来起作用,最坏的情况仍然是在没有选择时。

注意:假设SQL Server(差异为TOP 1LIMIT 1比较):

 @TheInsee int
AS
BEGIN
declare @Zone char(1)

SELECT @Zone = 
      CASE 
         WHEN (SELECT TOP 1 1 FROM LS_CLIENT_INSEE_A WHERE NO_INSEE = @TheInsee) >  0   THEN 'A'
         WHEN (SELECT TOP 1 1 FROM LS_CLIENT_INSEE_B WHERE NO_INSEE = @TheInsee) >  0   THEN 'B'
         WHEN (SELECT TOP 1 1 FROM LS_CLIENT_INSEE_C WHERE NO_INSEE = @TheInsee) >  0   THEN 'C' 
         WHEN (SELECT TOP 1 1 FROM LS_CLIENT_INSEE_D WHERE NO_INSEE = @TheInsee) >  0   THEN 'D'
         WHEN (SELECT TOP 1 1 FROM LS_CLIENT_INSEE_F WHERE NO_INSEE = @TheInsee) >  0   THEN 'F'
         WHEN (SELECT TOP 1 1 FROM LS_CLIENT_INSEE_P WHERE NO_INSEE = @TheInsee) >  0   THEN 'P'       
      END  
END

TOP 1 1是一种阻止它扫描整个表格的快捷方式,如果NO_INSEE没有编入索引并且表格很大,它将会在第一次点击时停止并且不会继续扫描整个表格。

答案 1 :(得分:1)

您可以删除所有@CountX变量并执行以下操作:

(SQL EXISTS()有效地检查是否至少单行退出并立即返回,因此它会比COUNT(*)更快,因为在找到第一行时退出)

SELECT @Zone = CASE WHEN EXISTS (
                           SELECT * FROM LS_CLIENT_INSEE_A 
                           WHERE NO_INSEE = @TheInsee 
                           )
                THEN 'A' END

...