Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored Procedure T-SQL If boolean check

An easy one for anyone who knows. In TSQL Stored Procedures how do you write an if statement comparing the value of a bool. Being accustomed to C# too long I'm putting in curly braces, round braces and all sorts and I think I'm getting it wrong.

like image 433
Sachin Kainth Avatar asked Jun 18 '12 15:06

Sachin Kainth


People also ask

How do you write an IF THEN statement in SQL?

Syntax. IF (a <= 20) THEN c:= c+1; END IF; If the Boolean expression condition evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing end if) will be executed.

How do you select a boolean in SQL?

SQL Server does not support a Boolean type e.g. SELECT WHEN CAST(1 AS BIT) THEN 'YES' END AS result -- results in an error i.e. CAST(1 AS BIT) is not the same logical TRUE.

Can you use if statements in SQL?

IF statements can be used to conditionally enter into some logic based on the status of a condition being satisfied. The IF statement is logically equivalent to a CASE statements with a searched-case-statement-when clause.


1 Answers

DECLARE @bool BIT = 1

IF @bool = 1
BEGIN
    -- do stuff here
    PRINT 'it was true';
END
ELSE
BEGIN
    -- do other stuff here
    PRINT 'it was not true';
END

If you've only got a single line inside the if then you don't need the BEGIN and END, but it's probably good practice to use them anyway.

like image 77
Jonathan Sayce Avatar answered Sep 17 '22 17:09

Jonathan Sayce