Incorrect syntax near ')'
How do I execute only one select statement based on user input i.e @id. Here is my syntax.
Create Procedure employee
@id int,
@year int
AS
SELECT CASE WHEN @id = 1 THEN
(select a.name, b.roles from employee a
INNER JOIN department b ON a.id = b.id
where b.years IN (@year)
OR b.roles IS NOT NULL )
ELSE CASE WHEN @id = 2 THEN
(select a.name, b.dayoff from employee a
INNER JOIN department b ON a.id = b.id
where b.years IN (@year)
OR b.dayoff IS NOT NULL )
Best Answer
One important thing to consider:
CASE
in T-SQL is an expression that returns a value, not control-of-flow logic like you might find in other languages (e.g. VB treats it like aswitch()
). In SQL Server, it can't be used this way; you can't say:All output from the
CASE
expression must happen at the same scope and within the same query. I've written quite a lengthy article about some of the more common misconceptions aboutCASE
here:In your scenario, if these are the only two potential outcomes, then you can probably follow @billspat's advice and just move the location of your
CASE
expression into theWHERE
clause of a single query.If your actual scenario is more complex (like you have 20 or 60 or 7000 different
@id
values that can lead to different forms of thatWHERE
clause, dynamic SQL might be a better solution (SQL Server will have a very hard time coming up with a single execution plan that is optimal for all variations of the query). Something like this:I talk about this in a little more detail here:
You could add logic to also dictate which output columns to show, but the application layer should be able to ignore output columns based on the
@id
value it passed in.And please, always use the schema prefix.