获取主键或任何其他属性只插入行后(Getting primary key or any other

2019-10-18 21:38发布

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

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

但上面的代码返回外键,这是插入查询的一部分中的一个。 我怎样才能在插入后返回主键? 其次,有没有什么办法刚刚插入后能得到任何特定属性。
我使用asp.net和SQL Server 2008

Answer 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的,等等等等),对于这种事情,因为它使你不必应付这种样板的,我会建议。



Answer 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


文章来源: Getting primary key or any other attribute just after inserting a row