BEGIN…END block in SQL Server

人盡茶涼 提交于 2019-12-12 03:37:33

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/36217599/begin-end-block-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!