在SQL Server 2005中使用IF THEN和GOTO

时间:2009-05-13 10:27:47

标签: sql-server-2005

以下是存储过程,其中iam传递DriverID = 0并且DrivarCode = DD1和DriverName = Ram。 执行控制将失败。控制即将到来   IF((@DriverName!= NULL)和((@DriverCode!= NULL)),之后失败.DriverName和DriverCode包含值。但仍然会失败。这可能是什么原因

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'

2 个答案:

答案 0 :(得分:3)

我甚至不确定这段代码是如何解析的。在存储过程结束后,您有“失败”,并且它不以冒号结束。你想要更像这样的东西:

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

答案 1 :(得分:1)

您可以使用以下代码来实现它。

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