如何在SQL Server存储过程中使用if else

时间:2020-06-11 10:32:37

标签: sql-server stored-procedures ssms-2017

存储过程:

CREATE PROCEDURE validate
    @blockID VARCHAR(255)
AS
BEGIN
    IF @blockID = (SELECT blockID FROM block WHERE blockID = @blockID)
        PRINT 'exists'

    IF @blockID != (SELECT blockID FROM block WHERE blockID = @blockID)
        PRINT 'does not exist'

END

输入错误的一个blockID时,如果条件不起作用则输入第二个。

1 个答案:

答案 0 :(得分:2)

您可能想使用EXISTS

CREATE PROCEDURE validate
   @blockID VARCHAR(255)
AS
BEGIN
   IF EXISTS (SELECT blockID FROM block WHERE blockID = @blockID)
      PRINT'exists'
   ELSE
      PRINT'not exists'
END