我对 xact_state 函数的错误提供的值有疑问。这是我的代码:
IF OBJECT_ID(N'dbo.Products', N'U') IS NOT NULL
DROP TABLE dbo.Products
CREATE TABLE Products (
ProductID int NOT NULL PRIMARY KEY,
ProductName nvarchar(100) null,
UnitPrice decimal(18,2) not null,
UnitsInStock int not null,
UnitsOnOrder int null,
DateIn datetime
);
GO
create or alter procedure InsertProduct(
@ProductId int,
@ProductName nvarchar(100),
@UnitPrice decimal(18,2),
@UnitsInStock int,
@UnitsOnOrder int
)
as
begin
begin try
begin transaction
insert into Products(ProductID, ProductName, UnitPrice, UnitsInStock, UnitsOnOrder, DateIn)
values(@ProductID, @ProductName, @UnitPrice, @UnitsInStock, @UnitsOnOrder, GETDATE())
commit transaction
end try
begin catch
print N'value of XACT_STATE()' + convert(nvarchar(20),XACT_STATE());
if XACT_STATE() = 1
begin
print N'Rollback Necessary'
rollback transaction
end;
throw 51000, N'There is an error with the application',1
end catch
end
GO
exec InsertProduct @ProductID = 1, @ProductName = 'B', @UnitPrice = 10.0, @UnitsInStock = 2, @UnitsOnOrder = 1
select * from Products
-- Generating an error
exec InsertProduct @ProductID = 1, @ProductName = 'C', @UnitPrice = 10.0, @UnitsInStock = 2, @UnitsOnOrder = 1
select * from Products
最后我收到了这个错误信息:
我的问题是,为什么这个函数的值是 1 而不是 -1,因为第二次插入对于违反主键定义是不可提交的。