为什么IF子句中有BEGIN和END而不是ELSE子句?

时间:2016-02-10 07:18:42

标签: sql-server tsql stored-procedures

有人可以解释为什么在示例中

DECLARE @compareprice money, @cost money 
EXECUTE Production.uspGetList '%Bikes%', 700, 
    @compareprice OUT, 
    @cost OUTPUT
IF @cost <= @compareprice 
BEGIN
    PRINT 'These products can be purchased for less than 
    $'+RTRIM(CAST(@compareprice AS varchar(20)))+'.'
END
ELSE
    PRINT 'The prices for all products in this category exceed 
    $'+ RTRIM(CAST(@compareprice AS varchar(20)))+'.'
https://msdn.microsoft.com/en-us/library/ms182717.aspx上的

有一个BEGINEND封闭了IF块,但不是ELSE块?

1 个答案:

答案 0 :(得分:3)

当只有一个语句时,

BEGINEND是可选的。在此示例中,IFELSE子句中不需要它们,因为只有一个语句。它可以这样写:

IF @cost <= @compareprice 
    PRINT 'These products can be purchased for less than 
    $'+RTRIM(CAST(@compareprice AS varchar(20)))+'.'
ELSE
    PRINT 'The prices for all products in this category exceed 
    $'+ RTRIM(CAST(@compareprice AS varchar(20)))+'.'