当我尝试从表中获取最后一个标识值时,为什么我得到null

时间:2012-06-15 08:42:36

标签: sql sql-server sql-server-2008 tsql sql-server-2005

我有一个表(日志表,它已作为ssis错误处理和日志记录的一部分创建)e在数据库中。我在此表中插入一行并尝试从表中获取最后一个标识值scope_identity()但是我为scope_identity获取 NULL ?()。请参阅dml语句和scope_identity()语句作为一个存储过程的一部分

insert into logging.execution_log
            (ParentLogID, Description, PackageName, PackageGuid, MachineName, ExecutionGuid, LogicalDate, Operator, StartTime, EndTime, Status,FailureTask)
        select @ParentLogID, @Description, @PackageName, cast(@PackageGuid as uniqueidentifier), @MachineName, cast(@ExecutionGuid as uniqueidentifier),
                @logicalDate, @operator, getdate(), null, @status, null



**set @LogID = cast(scope_identity() as int)**

但是当我尝试获取@logid的值时,它只返回null

请注意,logging.execution_log表的 LogId 列已有标识规范

此致

* 其他详细信息(我刚刚完成了一些测试时的理解) 作为测试的一部分,我已经手动插入了一些新行,如下所示 插入logging.execution_log             (ParentLogID,描述,PackageName,PackageGuid,MachineName,              ExecutionGuid,LogicalDate,Operator,StartTime,EndTime,Status,FailureTask)

    select 1, 2, 3, **NEWID()**,
     5, **NEWID()**,
            7, 8, getdate(), null, 0, null

select scope_identity()
select * from logging.execution_log

然后它显示身份的最后一个值.........它很好 但问题是当我将PackageGuid作为 system :: Packageid (ssis系统变量)和ExecutionGuid作为 system :: executioninstanceGUID 传递时,它确实正确地在表中插入行但我无法使用scope_identi或@@ identity或ident_current获取最后一个身份值(所有显示为null)*

2 个答案:

答案 0 :(得分:1)

使用输出到子句:

insert into logging.execution_log
            (ParentLogID, Description, PackageName, PackageGuid, MachineName, ExecutionGuid, LogicalDate, Operator, StartTime, EndTime, Status,FailureTask)
        output LogID into @LogID
        select @ParentLogID, @Description, @PackageName, cast(@PackageGuid as uniqueidentifier), @MachineName, cast(@ExecutionGuid as uniqueidentifier),
                @logicalDate, @operator, getdate(), null, @status, null

答案 1 :(得分:0)

begin try
    Set XACT_ABORT ON
    BEGIN TRAn
            INSERT into logging.execution_log
                (ParentLogID, Description, PackageName, PackageGuid, MachineName, 
                ExecutionGuid, LogicalDate, Operator, StartTime, EndTime, Status,FailureTask)
            Values(@ParentLogID, @Description, @PackageName, 
                cast(@PackageGuid as uniqueidentifier), @MachineName, 
                cast(@ExecutionGuid as uniqueidentifier),  @logicalDate, 
                @operator, getdate(), null, @status, null)

            Set @LogID = scope_identity()
    Commit Tran
End try

Begin Catch
    Select Error_Message();
    Rollback Tran
End Catch