Använder IF
(på rätt sätt)
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
Andra sätt (du bör undvika men jag postar som referens)
Använder dynamisk SQL
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)
Använder UNION
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 ...