【问题标题】:ASP.NET and SQL Server : update last record with dynamic valuesASP.NET 和 SQL Server:使用动态值更新最后一条记录
【发布时间】:2021-05-10 21:08:19
【问题描述】:

我正在检索一个 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();

【问题讨论】:

    标签: sql asp.net sql-server


    【解决方案1】:

    理解是您需要不断更新插入到 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"
    

    【讨论】:

    • 我确实有唯一的主键 ID,但第一条语句可以满足我的需要。谢谢,楚玛!
    猜你喜欢
    • 2012-11-29
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多