SQL Server and C#: get last inserted id

前端 未结 9 1057
执念已碎
执念已碎 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:33

    Use Stored Procedure only for the queries and use SCOPE_IDENTITY to get max value.

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

    OUTPUT clause?

    string query = "INSERT INTO SocialGroup (created_by_fbuid) 
                    OUTPUT INSERTED.IDCol  --use real column here
                    VALUES (@FBUID)";
    ...
    int lastId = (int)command.ExecuteScalar();
    
    0 讨论(0)
  • 2020-12-10 02:36
    cmd = new SqlCommand("Insert into table values (1,2,3); SELECT SCOPE_IDENTITY()", conn);
    
    lastRecord = cmd.ExecuteScalar().ToString();
    
    0 讨论(0)
  • 2020-12-10 02:38

    I'd recommend to use a stored procedure to do this. You can give it an OUTPUT parameter which you can use to return the id value back to your app.

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

    You can use ExecuteScalar to get the last value from a Sqlcommand.

    The scope_identity() function is safer than @@identity.

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

    U can try ExecuteScalar for getting the LastID value.

    0 讨论(0)
提交回复
热议问题