执行“插入”命令并在 Sql 中返回插入的 Id

我在 MVC 4中使用 C # 将一些值插入到一个 SQL 表中。实际上,我想插入值并返回上次插入的记录的“ ID”。我使用以下代码。

public class MemberBasicData
{
public int Id { get; set; }
public string Mem_NA { get; set; }
public string Mem_Occ { get; set; }
}

ID 在插入时在数据库中自动递增。

public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
using (SqlConnection con=new SqlConnection(Config.ConnectionString))
{
using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ)",con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();


int modified = cmd.ExecuteNonQuery();


if (con.State == System.Data.ConnectionState.Open) con.Close();
return modified;
}
}
}
   

我知道 ExecuteNonQuery表示影响行的数字。我用

int modified = (int)cmd.ExecuteScalar();

但是没有用。请帮我解决这个问题。有没有像 cmd.ExecuteInsertAndGetID()这样的代码(不与我的代码一起工作)。

335773 次浏览

将查询更改为

"INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ); SELECT SCOPE_IDENTITY()"

这将返回最后插入的 ID,然后可以使用 ExecuteScalar获得该 ID

下面的解决方案适用于 sqlserver2005及以上版本。可以使用 输出获取所需的字段。代替 id 你可以写你想要返回的密钥。像这样

FORSQLSERVER2005及以上版本

    using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) output INSERTED.ID VALUES(@na,@occ)",con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();


int modified =(int)cmd.ExecuteScalar();


if (con.State == System.Data.ConnectionState.Open)
con.Close();


return modified;
}
}

对于以前的版本

    using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ)  VALUES(@na,@occ);SELECT SCOPE_IDENTITY();",con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();


int modified = Convert.ToInt32(cmd.ExecuteScalar());


if (con.State == System.Data.ConnectionState.Open) con.Close();
return modified;
}
}
USE AdventureWorks2012;
GO
IF OBJECT_ID(N't6', N'U') IS NOT NULL
DROP TABLE t6;
GO
IF OBJECT_ID(N't7', N'U') IS NOT NULL
DROP TABLE t7;
GO
CREATE TABLE t6(id int IDENTITY);
CREATE TABLE t7(id int IDENTITY(100,1));
GO
CREATE TRIGGER t6ins ON t6 FOR INSERT
AS
BEGIN
INSERT t7 DEFAULT VALUES
END;
GO
--End of trigger definition


SELECT id FROM t6;
--IDs empty.


SELECT id FROM t7;
--ID is empty.


--Do the following in Session 1
INSERT t6 DEFAULT VALUES;
SELECT @@IDENTITY;
/*Returns the value 100. This was inserted by the trigger.*/


SELECT SCOPE_IDENTITY();
/* Returns the value 1. This was inserted by the
INSERT statement two statements before this query.*/


SELECT IDENT_CURRENT('t7');
/* Returns value inserted into t7, that is in the trigger.*/


SELECT IDENT_CURRENT('t6');
/* Returns value inserted into t6. This was the INSERT statement four statements before this query.*/


-- Do the following in Session 2.
SELECT @@IDENTITY;
/* Returns NULL because there has been no INSERT action
up to this point in this session.*/


SELECT SCOPE_IDENTITY();
/* Returns NULL because there has been no INSERT action
up to this point in this scope in this session.*/


SELECT IDENT_CURRENT('t7');
/* Returns the last value inserted into t7.*/
using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) " +
"VALUES(@na,@occ);SELECT SCOPE_IDENTITY();",con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();


int modified = cmd.ExecuteNonQuery();


if (con.State == System.Data.ConnectionState.Open) con.Close();
return modified;
}

SCOPE _ IDENTITY : 返回插入到同一作用域的标识列中的最后一个标识值。欲知详情,请访问 http://technet.microsoft.com/en-us/library/ms190315.aspx/rel = “ nofollow”http://technet.microsoft.com/en-us/library/ms190315.aspx

SQLServer 存储过程:

CREATE PROCEDURE [dbo].[INS_MEM_BASIC]
@na varchar(50),
@occ varchar(50),
@New_MEM_BASIC_ID int OUTPUT
AS
BEGIN
SET NOCOUNT ON;


INSERT INTO Mem_Basic
VALUES (@na, @occ)


SELECT @New_MEM_BASIC_ID = SCOPE_IDENTITY()
END

C # 代码:

public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
// values 0 --> -99 are SQL reserved.
int new_MEM_BASIC_ID = -1971;
SqlConnection SQLconn = new SqlConnection(Config.ConnectionString);
SqlCommand cmd = new SqlCommand("INS_MEM_BASIC", SQLconn);


cmd.CommandType = CommandType.StoredProcedure;


SqlParameter outPutVal = new SqlParameter("@New_MEM_BASIC_ID", SqlDbType.Int);


outPutVal.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outPutVal);
cmd.Parameters.Add("@na", SqlDbType.Int).Value = Mem_NA;
cmd.Parameters.Add("@occ", SqlDbType.Int).Value = Mem_Occ;


SQLconn.Open();
cmd.ExecuteNonQuery();
SQLconn.Close();


if (outPutVal.Value != DBNull.Value) new_MEM_BASIC_ID = Convert.ToInt32(outPutVal.Value);
return new_MEM_BASIC_ID;
}

我希望这些对你有帮助。

你也可以用这个,如果你想..。

public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
using (SqlConnection con=new SqlConnection(Config.ConnectionString))
{
int newID;
var cmd = "INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ);SELECT CAST(scope_identity() AS int)";


using(SqlCommand cmd=new SqlCommand(cmd, con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);


con.Open();
newID = (int)insertCommand.ExecuteScalar();


if (con.State == System.Data.ConnectionState.Open) con.Close();
return newID;
}
}
}
SELECT SCOPE_IDENTITY() AS 'Identity'

这将返回仅在当前范围内插入的标识值

SELECT @@IDENTITY AS 'Identity';

这不限于特定的范围 因此,这将返回标识列的最新值,而这个最新值不一定是来自同一作用域的标识值。

如果你使用 EF:

 Class Person{
public int Id {get;set;}
public string Name {get;set;}
}

设置 Name 值:

 Person p = new Person(){
Name = "James"
};
DbContext.Persons.Add(p);
DbContext.SaveChanges();


//p.Id = new Id from database
//p.Name = James

你只要保存它,你会从数据库中得到 ID。