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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With