如何向 SQL 查询中的 SQL Server 列添加加一 (+1)

2021-09-10 00:00:00 sql tsql sql-server

简单的问题是,如何将 MS Query 中的字段值加 1?我正在尝试使用参数化方法将 1 (+1) 添加到我的 SQL Server 数据库中的 int 列.类似于对变量的 i++ 操作.我正在使用以下方法:

The simple question is, how do you increment a field value in a MS Query by 1 ? I am trying to add 1 (+1) to an int column in my SQL Server database using a parametrized method. Similar to an i++ operation on a variable. I am using the following method:

public static int UpdateFieldCount(int parameterId)
{
    // variable to hold the number of rows updated or the success of the query
    int updatesuccess = 0;

    // build your connection string
    string connectionstring = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    SqlConnection conn = new SqlConnection(connectionstring);

    // build your SQL Query statement
    string SQLString = "UPDATE TableName SET TableField + 1 WHERE SomeFilterField = @ParameterID";        
    SqlCommand sqlcmd = new SqlCommand(SQLString, conn);
    sqlcmd.Parameters.AddWithValue("@ParameterID", parameterID);

    conn.Open();
    updatesuccess = sqlcmd.ExecuteNonQuery();

    conn.Close(); 

    return updatesuccess;
}

此方法在我的 sql 查询中抛出与加号 (+) 相关的以下错误:

This method is throwing the following error related to the plus sign (+) in my sql query:

'+' 附近的语法不正确.

Incorrect syntax near '+'.

描述:在执行当前 Web 请求期间发生了未处理的异常.请查看堆栈跟踪以获取有关错误及其在代码中的来源的更多信息.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

异常详细信息:System.Data.SqlClient.SqlException:+"附近的语法不正确.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near '+'.

源错误:

第 315 行:
第 316 行:conn.Open();
第 317 行:updatesuccess = sqlcmd.ExecuteNonQuery();
第 318 行:conn.Close();
第 319 行:

Line 315:
Line 316: conn.Open();
Line 317: updatesuccess = sqlcmd.ExecuteNonQuery();
Line 318: conn.Close();
Line 319:

源文件:c:\testdevlocation\appname\App_Code\ClassFileName.cs 行:317

Source File: c:\testdevlocation\appname\App_Code\ClassFileName.cs Line: 317

对此有什么建议吗?

推荐答案

您需要一个值和一个字段来分配它.值为TableField + 1,所以赋值为:

You need both a value and a field to assign it to. The value is TableField + 1, so the assignment is:

SET TableField = TableField + 1

相关文章