SCOPE_IDENTITY()返回NULL?

时间:2010-07-17 08:29:33

标签: sql sql-server-2008

我使用的是SQL Server 2008 Express,下面是SP,谁返回

  

(0行(s)受影响)

     

Msg 515,等级   16,状态2,程序   sp_AddCarrierFees,

     

第21行不能   将值NULL插入列   'attribute_value_id',表格   'MyDevSystem.dbo.shipping_fees';

     

柱   不允许空值。 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代替,但有可能得到其他用户制作的身份。

FIXED:我找到了原因,因为第一个插入语句失败了,所以为什么返回(0行受影响),在修复插入语句之后,它现在可以工作了。谢谢大家。

1 个答案:

答案 0 :(得分:1)

首先验证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:)

相关问题