本文介绍了SQL Server和C#:获取最后插入的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static void CreateSocialGroup(string FBUID)
{
    string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (@FBUID); SELECT @@IDENTITY AS LastID";

    using (SqlConnection connection = new SqlConnection(ConnectionString))
    {
        SqlCommand command = new SqlCommand(query, connection);
        command.Parameters.AddWithValue("@FBUID", FBUID);

        connection.Open();
        command.ExecuteNonQuery();
    }
}

这是做的正确方法?而如何在一个变量得到LastID?谢谢

Is this the right way to do it? And how do i get LastID in to a variable? Thanks

推荐答案

OUTPUT子句?

string query = "INSERT INTO SocialGroup (created_by_fbuid)
                OUTPUT INSERTED.IDCol  --use real column here
                VALUES (@FBUID)";
...
int lastId = (int)command.ExecuteScalar();

这篇关于SQL Server和C#:获取最后插入的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 17:51