简体   繁体   中英

how to increment an integer in sql c#

I am making a voting system. I have a problem adding a count(increment each time the candidate is voted) to each candidate that they voted.

My Vote Button code is :

    sc.Open();
        try
        {
            cmd = new SqlCommand("UPDATE TableVote SET Vcount=Vcount+1 WHERE id=@count", sc);

            cmd.Parameters.AddWithValue("@count", TxtPresID.Text);

            int res = cmd.ExecuteNonQuery();
            if (res > 0)
            {
                MessageBox.Show(TxtPresID.Text.ToString() + " Saved!");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            sc.Close();
        }

and my table is

我的sql

the result of Vcount is just NULL ..

空值

What am i doing wrong? or is my Sql statement correct?

Looks like your Vcount is NULL . As others have pointed out, you should make that column default to 0 or you could do this

UPDATE TableVote SET Vcount=ISNULL(Vcount, 0) + 1 WHERE id=@count

Set the default Value of Vcount to be 0. It shouldn't be a null column.

Here is the query

ALTER TABLE {TABLENAME} 
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} 
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}

ALTER TABLE TableVote 
ADD Vcount int NOT NULL 
CONSTRAINT  tablevote_vcount_default DEFAULT 0

Another option is to check, whether Vcount is NULL

UPDATE TableVote SET Vcount=ISNULL(Vcount, 0) + 1 WHERE id=@count

You shouldn't be updating the count row every time. if you have 2 votes incoming at the same time, it might have unpredictable consequences.

A better way would be to have a table "votes" and then insert a row for every vote, including the candidate ID, the voter ID and the date of vote. also means you can have historical data for different voters, and that you can easily change votes if needed.

Learn that

Null + 1 = Null

So your Vcount will always be null when adding 1.
Vcount must be not nullable, and it's default value muste be 0. Then when you will add 1 to 0, it will give you the good result.

You can also Change your SQL Statement so that zero is used if the VCOUNT-Column is null:

"UPDATE TableVote SET Vcount=ISNULL(Vcount, 0)+1 WHERE id=@count"

This is especially useful if you cannot change the database schema to be Not-Null and have a Default value.

Vcount必须具有默认的0值,而Not Null,cause是一个Int Field。

If i am not wrong why not just use your primary key for it ,

UPDATE TableVote SET Vcount= max(id)  WHERE id=@count

OR

If some id's are deleted and you don't want to keep records or count deleted votes then

  UPDATE TableVote SET Vcount= COUNT(id)  WHERE id=@count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM