Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case statement with end = 1 in T/SQL query

I'm hoping somebody can explain the below query to me as I'm not familiar with the syntax:

@[user1]   int,
@[user2]   varchar(10)

delete 
from [table name]
where [id] in (select [id]
            from [a diff table name]
            where [user1] = @[user1])
and (case
     when [user2] = 'some string' then 1
     when [table field] = @user2 then 1
     else 0
     end) = 1
and [other field] = 0
and [other field] = 0
and [other field]= 0

Firstly, I've obviously changed all variable/table names. Apologies if anything isn't clear. I get that the first part is a delete statement where it uses an in statement. That's fine. I also get the last part, with the multiple AND statements adding conditions to the WHERE clause.

It's the case statement I'm struggling with. I've two questions.

  1. What is the else 0 for? Is that attached to the when clause above it, so that if [table field] doesn't = the user2 variable passed in it is set to 0?
  2. What is the end = 1? I've tried googling but haven't found any examples of this form before.
like image 893
Andrew Martin Avatar asked Mar 17 '23 20:03

Andrew Martin


1 Answers

ELSE 0 means that the CASE statement will return 0 if neither of the WHEN statements are matched.

End = 1 is easier to understand if you think of it as

WHERE (CASE .... END) = 1
like image 171
Richard Avatar answered Apr 07 '23 20:04

Richard