SQL Server and C#: get last inserted id

前端 未结 9 1058
执念已碎
执念已碎 2020-12-10 02:18
public static void CreateSocialGroup(string FBUID)
{
    string query = \"INSERT INTO SocialGroup (created_by_fbuid) VALUES (@FBUID); SELECT @@IDENTITY AS LastID\";
         


        
相关标签:
9条回答
  • 2020-12-10 02:49
    SqlCommand command = new SqlCommand("select max(id) from SocialGroup ", connection);
    int lastId = (int)command.ExecuteScalar();
    
    0 讨论(0)
  • 2020-12-10 02:53

    Personally, I would re-write your code to use Parameters. You could either use an InputOutput parameter or an Output Parameter. However, using a Return Value in your SQL would also work.

    Full examples on this can be found on MSDN.

    I would also use Scope_Identity() rather than @@Identity this will ensure that you will reveice the ID that relates to the current transaction. Details on Scope_Identity can be found here.

    0 讨论(0)
  • 2020-12-10 02:54

    If your server supports the OUTPUT clause you could try it with this one:

    public static void CreateSocialGroup(string FBUID)
    {
        string query = "INSERT INTO SocialGroup (created_by_fbuid) OUTPUT INSERTED.IDENTITYCOL VALUES (@FBUID)";
    
        using (SqlConnection connection = new SqlConnection(ConnectionString))
        {
            SqlCommand command = new SqlCommand(query, connection);
            command.Parameters.AddWithValue("@FBUID", FBUID);
    
            connection.Open();
            var _id = command.ExecuteScalar();
        }
    }
    
    0 讨论(0)
提交回复
热议问题