I have 6 tables: LS_CLIENT_INSEE_A, B, C , etc. Each table contains only 1 field: INSEE.
I just want to know if my input exists in one of these tables and return the corresponding letter from the table name (A,B,C etc).
Is there another why to rewrite this:
@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
Is above query the best way of achieving this?
Thanks you in advance,
Stev
This should work by stopping the select once it finds a hit, worst case will still be when it’s in none of them.
Note: assuming SQL Server (difference being the
TOP 1compared toLIMIT 1):The
TOP 1 1is a shortcut to prevent it from scanning the entire table which is important ifNO_INSEEis not indexed and the table is large, it will stop when it gets the first hit and not continue to scan the entire table.