首页 > 解决方案 > ASP.NET 和 SQL Server:使用动态值更新最后一条记录

问题描述

我正在检索一个 HTTP 响应,我将这些值反序列化到一个 Azure SQL 数据库中。我找不到任何方法来格式化 SQL 命令以将字符串变量更新到表的最后一条记录中。目的是用每个新令牌覆盖最后一条记录,以避免数据库维护要求。我可以像下面的示例中那样静态地写入一个值,但我需要它由变量动态传递,这似乎由于某种原因而放弃了语法或命令执行。没有错误或异常被抛出——它只是不做任何事情。

有人对我如何实现这一目标有任何想法吗?下面列出了 SQL 特定代码以供参考。

dynamic access = JsonConvert.DeserializeObject(response.Content);
string accessToken = access.access_token;
string timestamp = centralTime.ToString();
    
System.Data.SqlClient.SqlConnection connect = new System.Data.SqlClient.SqlConnection(connectionString);

System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand();       
command.CommandType = System.Data.CommandType.Text;
               
// this works as needed to insert a new record where required, but builds record counts over time
// command.CommandText = @"INSERT INTO AccessTokens (Token, LastRefreshDate) VALUES (@Token, @LastRefreshDate)";
// command.Parameters.AddWithValue("@Token", accessToken);
// command.Parameters.AddWithValue("@LastRefreshDate", centralTime);

// I've tried as many variations as possible based on what's available online upon searching;  these are two examples that don't work
// command.CommandText = @"UPDATE TOP 1 * FROM AccessTokens (Token, LastRefreshDate) VALUES (@Token, @LastRefreshDate)";
// command.CommandText = @"UPDATE AccessTokens SET Token = " + accessToken + " , LastRefreshDate = " + timestamp;
                
// this will update the record with the new value, but it's static
command.CommandText = @"UPDATE AccessTokens SET Token = 12345";
    
string test = "test";

// attempting to update with a string variable does not work, which is the desired outcome in order to maintain only one record with a dynamically changing value over time
// command.CommandText = @"UPDATE AccessTokens SET Token = " + test;
    
command.Connection = connect;

connect.Open();
command.ExecuteNonQuery();
connect.Close();

标签: sqlasp.netsql-server

解决方案


理解是您需要不断更新插入到 AccessToken 表中的最后一个令牌。假设您的 LastRefreshDate 在毫秒内足够独特,这应该看起来像

command.CommandText = @"UPDATE AccessTokens set Token = @Token where LastRefreshDate = (select Max(LastRefreshDate) from AccessTokens)"

理想情况下,如果此令牌与一堆其他访问令牌一起存在,您将在该 AccessToken 中拥有一个唯一 ID,该 ID 仅限于特定 ID,例如:

command.CommandText = @"UPDATE AccessTokens set Token = @Token where LastRefreshDate = (select Max(LastRefreshDate) from AccessTokens and ID=@ID) and ID=@ID"

推荐阅读