【问题标题】:Getting primary key or any other attribute just after inserting a row插入行后获取主键或任何其他属性
【发布时间】:2013-10-31 09:52:39
【问题描述】:

我有一个带有主键、两个外键和其他属性的表。我想以一种在插入后应该返回主键的方式插入一行,我正在使用以下语句来执行查询

int MyId = (int)insert.ExecuteScalar();  

但上面的代码返回一个外键,它是插入查询的一部分。插入后如何获得主键返回?其次,有什么方法可以在插入后获取任何特定属性。
我正在使用 asp.net 和 Sql Server 2008

【问题讨论】:

    标签: asp.net sql-server insert


    【解决方案1】:

    在 SQL Server 中使用这样的表:

    create table test
    (
     id int identity primary key,
     data nvarchar(255)
    )
    

    您可以使用SCOPE_IDENTITY():(省略错误检查等)

    using System;
    using System.Data;
    using System.Data.SqlClient;
    
    namespace sqltest
    {
      class Program
      {
          static void Main(string[] args)
          {
            SqlParameter id = new SqlParameter("id",0);
            //parameter value can be set server side and will be returned to client
            id.Direction=ParameterDirection.Output; 
            string query="Insert into test values ('hello world');select @id=SCOPE_IDENTITY()";
            int lastID=0;
            using (SqlConnection conn = new SqlConnection("put your connection string here"))
            {
                conn.Open();
                using (SqlCommand comm = new SqlCommand(query, conn))
                {
                    comm.Parameters.Add(id);
                    comm.ExecuteNonQuery();
                    //id.Value now holds the last identity value
                    lastID = Convert.ToInt32(id.Value);
                }//end using comm
            }//end using conn
           }//end Main
        }
    }
    

    但老实说,如果可能的话,我会建议您对此类事情使用抽象(Linq2SQL、实体框架、NHibernate 等),因为它使您不必处理此类样板文件。

    【讨论】:

    • 它给出了 InvalidOperationException “String[0]:Size 属性的大小为 0 无效。”在 comm.ExecuteNonQuery();
    • @Rahman 我很抱歉原始代码包含缺少的{,我已经更新了一个完整的工作控制台应用程序示例,您只需要更改连接字符串。
    • 在查询中“@id”使用 asp.net 的语法是否正确?或者你可以只用 SCOPE_IDENTITY() 编写插入查询,我可以在 Sql Server 中执行它来查看我的查询是否正确(我第一次使用 SCOPE_IDENTITY())
    • @Rahman 不确定我是否理解这个问题,但您可以在任何使用 SQL Server (System.Data.SqlClient) 的 .net 应用程序中使用它,无论是 Winforms、ASP.NET、WPF 等。您可以也可以直接在 SQL Server 中使用它,例如存储过程。
    • 我被困在这里“lastID = Convert.ToInt32(id.Value);”它说 invalidCastException ......:(
    【解决方案2】:

    使用输出!!

    create table mytab(
          pk int identity primary key,
          data nvarchar(20)
        );
        go
    
        insert into mytab
        output inserted.pk
        values ('new item my PK');
        go
    

    【讨论】:

    • 如何使用 asp.net 将“输出插入的.pk”的结果存储在变量中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多