0

我的 SP 确实包含一个 DELETE 和一个 INSERT INTO 语句。如果 DELETE 语句成功,而 INSERT INTO 不成功,JAVA 将只查看第一条语句并得出整个 SP 执行成功的结论,这可能是错误的。

如果只有一个语句失败,我如何执行多个语句并在 JAVA 中获得异常。我已经在 SQL 中尝试过使用 TRY-CATCH,但一切都得出结论,所有语句都正确执行,因为第一个语句成功。

它是一个 MS SQL 2008 数据库

ALTER PROCEDURE [testing] 
    @bikes  varchar(8000), 
    @groupw varchar(4), 
    @name char(6)

AS
BEGIN


        DELETE CP_customer_kngr_corr_s WHERE knid in ('blue')

        DECLARE @pos INT
        DECLARE @len INT
        DECLARE @value varchar(8000)

        set @pos = 0
        set @len = 0
        set @bikes= @bikes  +','

        WHILE CHARINDEX(',', @bikes, @pos)>0 BEGIN
            set @len = CHARINDEX(',', @bikes, @pos+1) - @pos
            set @value = SUBSTRING(@bikes, @pos, @len)

            INSERT INTO [bikes]
               ([bikes])
            VALUES
                (@value)

            set @pos = CHARINDEX(',', @bikes, @pos+@len) +1
        END 
END
4

3 回答 3

1

What database is this? In most databases you can do a RAISEERROR when an operation fails. That would lead to an JDBCException been thrown.

You can check if the insert has succeeded by checking @@rowcount. If the number of rows effected is zero, you might want to throw an exception.

http://technet.microsoft.com/en-us/library/ms187316.aspx

于 2013-09-25T16:22:58.560 回答
1

如果删除的行数为零,您可以获得删除行数并引发错误,对于插入语句,您可以使用 try/catch 并在 catch 块中引发错误。

//Perform delete
select @@ROWCOUNT

if @@ROWCOUNT = 0
  //RAISE ERROR

BEGIN TRY
 //perform insert here 
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;

SELECT @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

-- Use RAISERROR inside the CATCH block to return 
-- error information about the original error that 
-- caused execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
           @ErrorSeverity, -- Severity.
           @ErrorState -- State.
           );

END CATCH;

还要检查返回的错误状态,ERROR_STATE然后再将其作为值传递给RAISERROR

干杯!!

于 2013-09-25T18:07:55.637 回答
0

我的 SP 中的问题 SET NOCOUNT ON;是没有设置。它返回删除成功而不是 SELECT 语句。

这是最终结果。

ALTER PROCEDURE [testing] 
    @bikes  varchar(8000), 
    @groupw varchar(4), 
    @name char(6)

AS
BEGIN
    SET NOCOUNT ON;

        DELETE CP_customer_kngr_corr_s WHERE knid in ('blue')

        DECLARE @pos INT
        DECLARE @len INT
        DECLARE @value varchar(8000)

        set @pos = 0
        set @len = 0
        set @bikes= @bikes  +','

        WHILE CHARINDEX(',', @bikes, @pos)>0 BEGIN
            set @len = CHARINDEX(',', @bikes, @pos+1) - @pos
            set @value = SUBSTRING(@bikes, @pos, @len)

            INSERT INTO [bikes]
               ([bikes])
            VALUES
                (@value)

            set @pos = CHARINDEX(',', @bikes, @pos+@len) +1
        END 
END
于 2013-09-26T07:18:54.037 回答