通过按钮单击增加表中字段的值

时间:2014-07-07 17:13:50

标签: asp.net sql-server sql-server-2008 tsql stored-procedures

我目前正在开展一项投票实施的项目。

现在,在我的数据库中,我有一个名为options的表,有2列optionId(bigint)和count(bigint),所有行中count的默认值为0。 我想通过点击按钮来增加特定的计数字段。

例如,我必须增加具有optionId =(已通过某个数字)的计数值(用于投票特定选项

我正在使用存储过程执行此操作,但不幸的是所有行都在增加

我想只更新一行

这是按钮点击时触发的代码

Int32 optionid = Convert.ToInt32(RadioButtonList1.SelectedValue);
        using (SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ManagerConnectionString"].ConnectionString))
        {
            Conn.Open();
            incrementTheVote.incrementVote(optionid);
        }

这是我调用存储过程的类(incrementTheVote)的定义

public class incrementTheVote
{
    public static int incrementVote(int optionid)
    {
        int rowsaffected = 0;
        using (SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ManagerConnectionString"].ConnectionString))
        {
            Conn.Open();
            SqlCommand cmd = new SqlCommand("incrementVote", Conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@optionid", SqlDbType.Int).Value = optionid;
            rowsaffected = cmd.ExecuteNonQuery();
        }
        return rowsaffected;
    }
}

这是存储过程

    ALTER PROCEDURE incrementVote
        (
        @optionid bigint
        )
    AS
    BEGIN TRANSACTION
    SELECT votes from options where optionid = @optionid
    UPDATE options
    SET votes = votes + 1 
    COMMIT TRANSACTION

1 个答案:

答案 0 :(得分:3)

你太近了! 您需要在update语句中添加where子句 此外,更新可以引用其旧值,因此无需创建中间变量@votes。

ALTER PROCEDURE incrementVote
    (
    @optionid bigint
    )
AS
BEGIN TRANSACTION

UPDATE options
SET votes = votes + 1 
Where optionid = @optionid

COMMIT TRANSACTION