Sachin Kainth
Sachin Kainth

Reputation: 46750

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.

Upvotes: 17

Views: 78762

Answers (3)

Elnur
Elnur

Reputation: 111

Starting with SQL Server 2012 IIF is shorthand way of writing IF THEN ELSE for assignment:

    DECLARE @str VARCHAR(10);
    SET @str = IIF(1=1, 'Yes', 'No');

Upvotes: 3

Jonathan Sayce
Jonathan Sayce

Reputation: 9669

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.

Upvotes: 40

Dimitri
Dimitri

Reputation: 7013

The corresponding sql data type to boolean is bit, meaning 1 for true and 0 for false, so:

IF( @Statement=1)
    BEGIN
        SELECT COUNT(*) FROM Table
    END
ELSE
    BEGIN
        SELECT MIN(ID) FROM Table
    END
END

Upvotes: 3

Related Questions