2013-10-14 168 views
32

簡單的問題是,如何將MS Query中的字段值增加1?我正在嘗試使用參數化方法在我的SQL Server數據庫的int列中添加1(+1)。類似於變量上的i ++操作。我使用下面的方法:如何在SQL查詢中向SQL Server列添加+1(+1)

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查詢相關的加號(+)以下錯誤:

Incorrect syntax near '+'.

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.

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

Source Error:

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

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

對此有何建議?

回答

47

您需要一個值和一個字段來指定它。值爲TableField + 1,所以賦值爲:

SET TableField = TableField + 1 
48
"UPDATE TableName SET TableField = TableField + 1 WHERE SomeFilterField = @ParameterID"