How to use case statement inside SQL select Query

I need to get the result of the selected query depending on certain conditions

So if(id=uid)

I need the following request

select * from table1 where id=5;

      

more I need below

select * from table1 where id=10

      

I know I can use a condition to do this. But my query is very long, so when I use if else then it looks like

if(@id=@uid)
begin
select * from table1 where id=5;// query 1
end
else
select * from table1 where id=10;//query 2

      

but here I need to replace the whole query again for one check. Hopefully I can do something like this:

declare @id int=4;
declare @uid=10;

select * from table1 where 
case 
when @id=@uid
then 
id=5
else
id=10;
end

      

Update

I need one more condition

in this case id = 5 and uid = 10

then if(id=uid)

      

then

select * from table1 where id=5

      

and

if(id!=uid)

      

then

select * from table1

      

something like that

+3


source to share


3 answers


You can use an expression case

to return the value id

must be:

SELECT *
FROM   table1 
WHERE  id = CASE WHEN @id = @uid THEN 5 ELSE 10 END;

      

EDIT:

The updated requirement in the question is to return all rows when @id != @uid

. This can be done by comparing id

with id

:



SELECT *
FROM   table1 
WHERE  id = CASE WHEN @id = @uid THEN 5 ELSE id END;

      

Alternatively, given this updated requirement, a simple expression or

may be easier to use:

SELECT *
FROM   table1 
WHERE  @id = @uid OR id = 5;

      

+7


source


SELECT 
    *
FROM
    table1
WHERE
(
    @id = @uid
    AND
    id =5
)
OR
(
    not @id = @uid
    AND
    id=10
) 

      



+2


source


SELECT * FROM table1
WHERE (id=5 AND @id=@uid) OR (id=10 AND @id<>@uid)

      

+2


source







All Articles