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转换成变量?谢谢

OUTPUT子句?

string query = "INSERT INTO SocialGroup (created_by_fbuid) 
                OUTPUT INSERTED.IDCol  --use real column here
                VALUES (@FBUID)";
...
int lastId = (int)command.ExecuteScalar();
http://stackoverflow.com/questions/6109634/sql-server-and-c-get-last-inserted-id

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:SQL Server和C#:获取最后插入的ID