【问题标题】:How to add plus one (+1) to a SQL Server column in a SQL Query如何在 SQL 查询中向 SQL Server 列添加加一 (+1)
【发布时间】:2013-10-14 22:08:13
【问题描述】:

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

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 查询中抛出与加号 (+) 相关的以下错误:

“+”附近的语法不正确。

说明:在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

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

来源错误:

第 315 行:
第 316 行:conn.Open();
第 317 行:更新成功 = sqlcmd.ExecuteNonQuery();
第 318 行:conn.Close();
第 319 行:

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

对此有何建议?

【问题讨论】:

    标签: sql sql-server tsql


    【解决方案1】:

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

    SET TableField = TableField + 1
    

    【讨论】:

      【解决方案2】:
      "UPDATE TableName SET TableField = TableField + 1 WHERE SomeFilterField = @ParameterID"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-19
        • 2018-09-07
        • 2021-08-30
        • 2016-05-24
        • 2016-11-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多