Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

syntax error when using CASE in where clause

A similar question has been asked here

Anyway i get a syntax error i cannot figure.

This is my code:

declare @MyParameter integer
se @MyParameter = Set At Runtime (could be -1 or any value >=1)

SELECT manyfields FROM manyjoinedtables
where
 case when @MyParameter> -1 then 
 (FIELD1 **=** @MyParameter AND ANOTHERFIELD = Value**)**
 end -- note: in case @MyParameter  = -1 i do not want to add where condition

Anyway Management studio underlines in red the 2 chars surrounded by ** above.

Why? Where is the syntax error?

like image 639
LaBracca Avatar asked Jul 08 '26 22:07

LaBracca


1 Answers

Give this a go;

DECLARE @MyParameter INT
SET @MyParameter = Set At Runtime (could be -1 or any value >=1)

SELECT manyfields 
FROM manyjoinedtables
WHERE
    @MyParameter <= -1
OR
(
    @MyParameter > -1
    AND FIELD1 = MyParameter 
    AND AnotherField = Value
)
like image 176
Rich Benner Avatar answered Jul 11 '26 16:07

Rich Benner