gpt4 book ai didi

c# - 更新或插入新值

转载 作者:行者123 更新时间:2023-11-30 19:43:20 25 4
gpt4 key购买 nike

我在 asp.net 中有以下 SQL 命令:

cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO userscore (username, score)VALUES(@username, @score)";
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@score", userscore);
cmd.ExecuteNonQuery();

此命令有效,但每次单击按钮都会在我的 sql 数据库中存储两个值。它从文本框中获取分数值,但是当用户名+分数已经在数据库中时,我想更新该值。有人可以帮我查询以完成这项工作吗?

澄清我的问题:我想存储新分数,即使它低于当前分数,并且用户名在表中是唯一的。

最佳答案

我假设您只想为每个用户名存储一个最高分,而不是只存储一个全局最高分。

DECLARE @highscore int NULL
SELECT @highscore = MAX(score) FROM userscore WHERE username = @username

IF @highscore IS NULL BEGIN

INSERT INTO userscore ( username, score ) VALUES ( @username, @score )

END ELSE IF @score > @highscore BEGIN

UPDATE userscore SET score = @score WHERE username = @username

END

此 T-SQL 脚本需要两个参数,@username@score@highscore 变量在脚本中声明。

关于c# - 更新或插入新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15440773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com