无法在C#ASP.NET中获取上次事务ID

时间:2013-02-13 19:56:53

标签: c# asp.net sql-server webforms

我有以下代码运行存储过程:

    [WebMethod]
    public static string addNewNote(string id, string txt)
    {
        Guid parentId = new Guid(id);
        DbProviderFactory dbf = DbProviderFactories.GetFactory();
        using (IDbConnection con = dbf.CreateConnection())
        {
            con.Open();
            using (IDbTransaction trn = con.BeginTransaction())
            {

                Guid noteId = Guid.Empty;
                SqlProcs.spNOTES_WebForms
                        (ref noteId,
                        parentId,
                        "Files",
                        "Client Note",
                        txt,
                        true
                        );

                IDbCommand cmd = con.CreateCommand();
                cmd.CommandText = "SELECT SCOPE_IDENTITY()";
                cmd.Transaction = trn;

                // Get the last inserted id.
                string insertID = cmd.ExecuteScalar().ToString();
                Debug.Print(insertID.ToString());
            }
        }
        return "";
    }

它不会在输出面板中输出任何内容。如何检索最后一个ID?

注意:我的ID是GUID(uniqueidentifier)。

修改

这是我的存储过程:

if exists (select * from dbo.sysobjects where id = object_id(N'spNOTES_WebForms') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
    Drop Procedure dbo.spNOTES_WebForms;
GO

Create Procedure dbo.spNOTES_WebForms
    ( @ID                   uniqueidentifier output
    , @PARENT_ID            uniqueidentifier
    , @PARENT_TYPE          nvarchar(255)
    , @MODIFIED_USER_ID     uniqueidentifier
    , @NAME                 nvarchar(255)
    , @DESCRIPTION          ntext
    , @VISIBLE_TO_CLIENT    bit
    )
with encryption
as
  begin
    set nocount on

    if dbo.fnIsEmptyGuid(@ID) = 1 begin -- then
        set @ID = newid();
    end -- if;
    insert into NOTES
        ( ID               
        , PARENT_ID
        , PARENT_TYPE
        , CREATED_BY       
        , DATE_ENTERED     
        , MODIFIED_USER_ID 
        , DATE_MODIFIED    
        , NAME             
        , DESCRIPTION      
        , VISIBLE_TO_CLIENT
        )
    values
        ( @ID               
        , @PARENT_ID
        , @PARENT_TYPE
        , @MODIFIED_USER_ID 
        ,  getdate()        
        , @MODIFIED_USER_ID 
        ,  getdate()        
        , @NAME             
        , @DESCRIPTION      
        , @VISIBLE_TO_CLIENT
        );

    -- 03/04/2006 Paul.  Add record to custom table. 
    if not exists(select * from NOTES_CSTM where ID_C = @ID) begin -- then
        insert into NOTES_CSTM ( ID_C ) values ( @ID );
    end -- if;

  end
GO

Grant Execute on dbo.spNOTES_WebForms to public;
GO

1 个答案:

答案 0 :(得分:0)

首先你应该检查isDBNull吗?并且您的查询未返回任何ID。 string id = cmd.ExecuteScalar(); 添加SELECT SCOPE_IDENTITY();您的查询结束,然后重试。 Scope_Identity()也返回一个小数。您可以对查询结果使用Convert.ToInt32,也可以将返回值转换为十进制,然后再转换为int。