问题
Consider the following table:
CREATE TABLE [dbo].[OrderingTest](
[ColKey] [int] IDENTITY(1,1) NOT NULL,
[Col0] [int] NULL,
[Col1] [int] NOT NULL,
[Col2] [int] NOT NULL
) ON [PRIMARY]
... and the following batch:
BEGIN
INSERT INTO OrderingTest(Col0,Col1,Col2)
VALUES (1,NULL,3);
SELECT SCOPE_IDENTITY();
END;
The Test table does not allow NULL values in Col1, so the insert will fail. I was hoping to test for failure using the value of SCOPE_IDENTITY() at this point. However, instead of seeing the SELECT SCOPE_IDENTITY() produce a single row with a NULL column as output, execution of the batch terminates after the failed insert and the SELECT SCOPE_IDENTITY() line is never executed.
UPDATE:
I was incorrect the result of SCOPE_IDENTITY() was displayed in the Results pane. I was confused, because SSMS switched the Messages pane into focus instead of the Results pane (since an error occurred).
However the latest value of the identity column, ColKey, is displayed instead of NULL after a failed INSERT. I thought SCOPE_IDENTITY() is supposed to return NULL if an INSERT fails.
回答1:
I tried these commands:
BEGIN
DECLARE @theKey INT
BEGIN TRY
INSERT INTO OrderingTest(Col0,Col1,Col2)
VALUES (1,NULL,3);
SELECT @theKey = SCOPE_IDENTITY();
END TRY
BEGIN CATCH
SET @theKey = - 1
END CATCH
select @theKey
END;
And the following
BEGIN
DECLARE @theKey INT
SET @theKey = 1
INSERT INTO OrderingTest(Col0,Col1,Col2)
VALUES (1,NULL,3);
SELECT @theKey = SCOPE_IDENTITY();
select @theKey
END;
In both cases, the SELECT @theKey was executed, although in the second example, an error message was displayed to the print window. Note that in your example, you are trying to insert into the TEST table, rather than OrderingTest table. This will produce an error and not run the SELECT. Are you sure your example is right?
Note that in this example, SCOPE_IDENTITY returns the identity from the last successful INSERT, not NULL
BEGIN
INSERT INTO OrderingTest(Col0,Col1,Col2) VALUES (1,2,3);
INSERT INTO OrderingTest(Col0,Col1,Col2) VALUES (1,NULL,3);
SELECT SCOPE_IDENTITY();
END;
来源:https://stackoverflow.com/questions/8273885/how-can-i-continue-execution-of-the-current-block-after-an-insert-failure