Sql SCOPE_IDENTITY()返回空值?
我使用的是SQLServer2008Express,下面是返回的SP (受影响的0行) 味精515,电平 第16条,第2款,程序 sp_AddCarrierFees 第21行不能 将值NULL插入到列中 “属性值id”,表 “MyDevSystem.dbo.运费” 纵队 不允许空值。插入失败。 声明已终止 (1行受影响) 这是SP:Sql SCOPE_IDENTITY()返回空值?,sql,sql-server-2008,Sql,Sql Server 2008,我使用的是SQLServer2008Express,下面是返回的SP (受影响的0行) 味精515,电平 第16条,第2款,程序 sp_AddCarrierFees 第21行不能 将值NULL插入到列中 “属性值id”,表 “MyDevSystem.dbo.运费” 纵队 不允许空值。插入失败。 声明已终止 (1行受影响) 这是SP: GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[sp_Ad
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或IDENTITY\u CURRENT,但它可能获得了其他用户的身份
修复:我找到了原因,因为第一条insert语句失败,所以为什么返回(受影响的0行),在修复该insert语句后,它现在可以工作了。谢谢大家。首先验证
shipping\u属性值
是否实际具有标识
列。如果没有标识列,scope\u identity()
编辑:我没注意到插入的实际上使用的是选择的,但是马克注意到了:)*抓了咖啡*
进行单独的选择以查看输出如何:
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\u identity()
应为null:)能否发布shipping\u属性值表的定义?是的,创建表[dbo]。[shipping\u属性值]([attribute\u值id][int]identity(1,1)不为null,[attribute\u id][int]不为null,[attribute\u值][varchar 255]不为null,[sort_order][int]不为空,约束[PK_shipping_attribute_value]主键聚集([attribute_value_id]ASC),在[PRIMARY]上的[PAD_INDEX=OFF,STATISTICS_NorecoComputer=OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=ON,ALLOW_PAGE_LOCKS=ON)]主键上的属性_value_id是主键,自动递增1