sql-serverstored-proceduresssms-17

How to use if else in SQL Server stored procedure


Stored procedure:

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

When input the wrong one blockID, the 2nd if conditions does not work.


Solution

  • You probably want to use 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