[英]SCOPE_IDENTITY() return NULL?
我正在使用SQL Server 2008 Express,下面是SP,谁退
(0行受影响)
消息515,级别16,状态2,过程sp_AddCarrierFees,
第21行无法将值NULL插入表'MyDevSystem.dbo.shipping_fees'的'attribute_value_id'列中;
列不允许为空。 INSERT失败。 该语句已终止。
(影响1行)
这就是SP:
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_AddCarrierFees]
@carrier_id INT,
@zone_id INT,
@attribute_value_id INT,
@attribute_title varchar(20),
@fees decimal(6,2)
AS
BEGIN
if @attribute_value_id = 0 begin
insert into shipping_attribute_value (attribute_id,attribute_value,sort_order)
select attribute_id, @fees,0 from shipping_attribute where carrier_id=@carrier_id and attribute_title=@attribute_title;
declare @NewID int;
set @NewID = SCOPE_IDENTITY();
print @NewID;
insert into shipping_fees (zone_id, attribute_value_id) values (@zone_id, @NewID);
end
else
begin
update shipping_attribute_value set attribute_value=@fees where attribute_value_id=@attribute_value_id;
end
END
有人知道为什么吗? 我已经在StackOverFlow上阅读了很多文章,但是仍然找不到解决方案。有人说使用@@ IDENTITY或IDENT_CURRENT来代替,但是可能得到其他用户的身份。
修正:我找到了原因,因为第一个插入语句失败,所以为什么在我修复该插入语句后返回(0行受影响),现在可以工作了。 谢谢大家
首先,验证shipping_attribute_value
实际上具有一个identity
列。 没有标识列, scope_identity()
将不起作用。
编辑:我错过了insert
实际上是使用select
,但marc_s注意到了:) *抓咖啡*
只看输出结果如何做一个单独的选择:
select attribute_id, @fees,0 from shipping_attribute
where carrier_id=@carrier_id and attribute_title=@attribute_title;
insert into shipping_attribute_value (attribute_id,attribute_value,sort_order)
select attribute_id, @fees,0 from shipping_attribute
where carrier_id=@carrier_id and attribute_title=@attribute_title;
如果没有插入行, scope_identity()
应该为null :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.