Search code examples
sql-servert-sqlcaseiif

BEGIN...END block in SQL Server


Are there any rules defined for grouping the T-SQL statements under the BEGIN...END block ?

Because when I try the BEGIN...END block inside the CASE statement OR IIF statement, it fails.

I need BEGIN...END block because there are multiple operations that I want to perform under the CASE result.

SELECT 
CASE @ChargePaid
WHEN 1 THEN 
            BEGIN 
             SELECT 'Paid'
            END
WHEN 0 THEN 
            BEGIN 
             SELECT 'Not Paid'
            END
END

OR

SELECT IIF( @ChargePaid > 0, BEGIN SELECT 'Paid' END , BEGIN SELECT 'Not Paid' END )

EDIT:

IF @cond = 'First'
WITH CTE AS (
             SELECT 'A missing' Result
             UNION 
             SELECT 'B missing' Result
             UNION 
             SELECT 'C missing' Result
)
SET @msg = SELECT Result from CTE 

IF @cond = 'Second'
WITH CTE AS (
              SELECT 'A missing' Result
              UNION 
              SELECT 'B missing' Result
              UNION 
              SELECT 'C missing' Result
)
SET @msg = SELECT Result from CTE 

IF @ChargePaid = 0
...
Some code goes here to generate the message.
Then I store the actual message into @msg variable.
...

In the end I store the @msg values (I trim the @msg if it requires) to the table. 

What I want is:

I want to validate the @ChargePaid condition. If it comes false, I want to avoid further processing for optimization of code & store charge missing info to @msg variable\table.


Solution

  • BEGIN / END delimit program statements.

    Encloses a series of Transact-SQL statements so that a group of Transact-SQL statements can be executed.

    CASE blocks accept expressions.

    Evaluates a list of conditions and returns one of multiple possible result expressions.

    So you are trying to fit a square peg in a round hole.