Using IF THEN and GOTO in SQL Server 2005

Below is a stored procedure where iam passes DriverID = 0 and DrivarCode = DD1 and DriverName = Ram. The control crashes during execution. IF ((@DriverName! = NULL) and ((@DriverCode! = NULL)), After that it will fail. DriverName and DriverCode contain values. But it still fails. What could be the reason for this

Create Procedure InsertUpdateM
(
    @DriverID int,
    @DriverCode varchar(50),
    @DriverName varchar(50),
    @Msg varchar(50) output
)

AS
BEGIN
IF @DriverID=0
    BEGIN
        SELECT DriverName,DriverCode FROM DriverM WHERE DriverName=@DriverName and DriverCode=@DriverCode
        IF(@@RowCount>0) GOTO Fails
            IF ((@DriverName!=NULL) and ((@DriverCode!=NULL))
                BEGIN
                    INSERT INTO DriverM(DriverCode,DriverName) values(@DriverCode,@DriverName)
                END
    END
ELSE
    BEGIN
        SELECT DriverName,DriverCode FROM DriverM WHERE DriverName=@DriverName and DriverCode=@DriverCode
        IF(@@RowCount>0) GOTO Fails
            IF ((@DriverName!=NULL) and ((@DriverCode!=NULL)
                BEGIN
                    UPDATE DriverM SET DriverCode=@DriverCode,DriverName=@DriverName WHERE DriverID=@DriverID
                END
    END
END

Fails
    SET @Msg='Failed'

      

0


a source to share


2 answers


I don't even know how this code parses. You have "Fails" after your stored procedure ends, and it doesn't end with a colon. You need something more:



ELSE
    BEGIN -- Begin 1
        SELECT DriverName,DriverCode FROM DriverM WHERE DriverName=@DriverName and DriverCode=@DriverCode
        IF(@@RowCount>0) GOTO Fails
            IF ((@DriverName!=NULL) and ((@DriverCode!=NULL)
                BEGIN -- Begin 2
                    UPDATE DriverM SET DriverCode=@DriverCode,DriverName=@DriverName WHERE DriverID=@DriverID
                END  -- End of 2
    END -- End of 1

GOTO Succeeds
Fails:
    SET @Msg='Failed'
Succeeds:
END -- End of SP

      

+3


a source


You can use the following code to achieve it.



Driverid:
    IF EXISTS(your query to check)
    BEGIN
        GOTO Driverid
    END

      

+1


a source







All Articles