ant*_*liu 170 c# sql sql-server
我有这个代码:
string insertSql =
"INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(@UserId, @GameId)";
using (SqlConnection myConnection = new SqlConnection(myConnectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
myCommand.Parameters.AddWithValue("@UserId", newUserId);
myCommand.Parameters.AddWithValue("@GameId", newGameId);
myCommand.ExecuteNonQuery();
myConnection.Close();
}
Run Code Online (Sandbox Code Playgroud)
当我插入这个表时,我有一个auto_increment int主键列调用GamesProfileId
,如何在此之后获取最后一个插入的列,以便我可以使用该id插入另一个表?
gbn*_*gbn 254
对于SQL Server 2005+,如果没有插入触发器,则将insert语句(所有一行,为清晰起见,将此处拆分)更改为此
INSERT INTO aspnet_GameProfiles(UserId,GameId)
OUTPUT INSERTED.ID
VALUES(@UserId, @GameId)
Run Code Online (Sandbox Code Playgroud)
对于SQL Server 2000,或者如果存在插入触发器:
INSERT INTO aspnet_GameProfiles(UserId,GameId)
VALUES(@UserId, @GameId);
SELECT SCOPE_IDENTITY()
Run Code Online (Sandbox Code Playgroud)
然后
Int32 newId = (Int32) myCommand.ExecuteScalar();
Run Code Online (Sandbox Code Playgroud)
jas*_*son 38
您可以创建一个CommandText
等于的命令
INSERT INTO aspnet_GameProfiles(UserId, GameId) OUTPUT INSERTED.ID VALUES(@UserId, @GameId)
Run Code Online (Sandbox Code Playgroud)
并执行int id = (int)command.ExecuteScalar
.
这篇MSDN文章将为您提供一些其他技巧.
string insertSql =
"INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(@UserId, @GameId)SELECT SCOPE_IDENTITY()";
int primaryKey;
using (SqlConnection myConnection = new SqlConnection(myConnectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
myCommand.Parameters.AddWithValue("@UserId", newUserId);
myCommand.Parameters.AddWithValue("@GameId", newGameId);
primaryKey = Convert.ToInt32(myCommand.ExecuteScalar());
myConnection.Close();
}
Run Code Online (Sandbox Code Playgroud)
这个工作:)
归档时间: |
|
查看次数: |
202252 次 |
最近记录: |