执行插入命令并在Sql中返回插入的ID


111

我正在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()(不能与我的代码一起使用)。


你是什​​么意思InsertedID
SonerGönül13年

Answers:


211

以下解决方案适用于sql server 2005及更高版本。您可以使用输出来获取必填字段。您可以使用ID代替ID编写要返回的密钥。像这样做

对于SQL SERVER 2005及更高版本

    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;
    }
}

1
int修改=(int)cmd.ExecuteScalar();
neel 2013年

10
请注意,列名必须与表的标识列名匹配。例如,具有以下标识列名称的表:select EmployeeId, * from Employees在insert语句中需要此片段:output inserted.EmployeeId
joshjeppson 2014年

在这种情况下,您将如何检查查询是否确实进行了插入?
ATD

8
尝试将in强制int modified = (int)cmd.ExecuteScalar();转换为int 时,出现无效的强制转换错误。我必须使用Convert将其转换为int。int modified = Convert.ToInt32(cmd.ExecuteScalar());
Baddack

下面的修改对我有用。INSERT INTO Mem_Basic(Mem_Na,Mem_Occ)输出INSERTED.ID VALUES(?,?)
ABB

45

将查询更改为

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

这将返回最后插入的ID,然后您可以获取 ExecuteScalar


1
这显示了一个错误“用户代码未处理InValidCast异常”
neel 2013年

2
@neel,这是因为scope_identity()返回数字数据类型,您只能将其转换为十进制.net数据类型。另一种方法是使用Convert.To <datatype>()系列函数来避免强制转换问题。
严苛的2013年

2
这个答案更好,因为您不必键入要插入的表的ID列。
goamn

1
SELECT SCOPE_IDENTITY()对我不起作用,但输出INSERTED.ID是有效的。
TiggerToo

1
@TiggerToo:您正在使用哪个版本的SQL Server?微软可能最终弃用了SCOPE_IDENTITY()OUTPUT INSERTED自从出现在IIRC SQL Server 2008中以来,一直是这样做的首选方式
Ken Keenan

19

SQL Server存储过程:

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;
        }
    }
}

0
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.*/

0
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/zh-cn/library/ms190315.aspx


3
很好,但是ExecuteNonQuery仅返回受影响的行数,而不返回ID。使用ExecuteScalar代替docs.microsoft.com/en-us/dotnet/api/…–
Brandtware
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.