0

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

    [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(唯一标识符)。

编辑:

这是我的存储过程:

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
4

1 回答 1

0

首先你应该检查 isDBNull 与否?而且您的查询没有返回任何 id。字符串 id = cmd.ExecuteScalar(); 添加SELECT SCOPE_IDENTITY();查询的结尾,然后重试。Scope_Identity() 也返回一个小数。您可以对查询结果使用 Convert.ToInt32,也可以将返回值转换为十进制然后转换为 int。

于 2013-02-13T20:14:38.313 回答