IF
gebruiken (op de juiste manier)
IF @Var = 'AA'
BEGIN
SELECT ID FROM Table1
-- WHERE ...
END
ELSE IF @Var = 'BB'
BEGIN
SELECT ID FROM Table2
-- WHERE ...
END
ELSE
BEGIN
SELECT ID FROM Table3
-- WHERE ...
END
Andere manieren (die je moet vermijden, maar ik post ter referentie)
Dynamische SQL gebruiken
DECLARE @sql NVARCHAR(MAX)
SELECT @sql = 'SELECT ID FROM ' + CASE @Var WHEN 'AA' THEN 'Table1'
WHEN 'BB' THEN 'Table2' ELSE 'Table3' END + ' -- WHERE ...'
EXEC(@sql)
UNION
gebruiken
SELECT Id
FROM Table1
WHERE @Var='AA'
-- AND ...
UNION ALL
SELECT Id
FROM Table2
WHERE @Var='BB'
-- AND ...
UNION ALL
SELECT Id
FROM Table3
WHERE @Var NOT IN('AA', 'BB')
-- AND ...