简体   繁体   中英

Auto increment to SQL Server in c#

I have this database that I created programmatically:

在此处输入图片说明

Here is the code I used to create the database:

using (SqlConnection conn = new SqlConnection(@"Data source = **** ; Database=******* ; User Id=***** ; Password=*******"))
{
    int i = 0;
    i++;

    conn.Open();

    string sqlQuery = @"INSERT INTO UXFaturas(IDNumFaturas, NumFaturas , Cliente, Valor, Data) VALUES (@idnumfaturas, @numfaturas, @client, @valor, @data)";

    SqlCommand SQLcm = new SqlCommand();
    SQLcm.Connection = conn;
    SQLcm.CommandText = sqlQuery;
    SQLcm.CommandType = CommandType.Text;

    SQLcm.Parameters.AddWithValue("@idnumfaturas", i);
    SQLcm.Parameters.AddWithValue("@numfaturas", numfatura);
    SQLcm.Parameters.AddWithValue("@client", nomecli);
    SQLcm.Parameters.AddWithValue("@valor", valorStr);
    //SQLcm.Parameters.AddWithValue("@estado", cont); no variable yet
    SQLcm.Parameters.AddWithValue("@data", data);

    SQLcm.ExecuteNonQuery();

    MessageBox.Show("inseriu");
    conn.Close();

    MessageBox.Show("gravou");
}

I need to make the IDNumFaturas an auto-increment. The way I tried didn't work. I've also tried to make it as primary key but if I do it I can't add nothing into the table. Any suggestion? I'm working with C#

your tables should have been created with

INT NOT NULL IDENTITY(1,1), 

on the primary key field.

Or go into your table builder and set Identity to Yes and set the seed to 1, increment to 1

What you need to do is understand what an identity is in SQL server

If you want to add an identity column at this stage, it will be a table rebuild meaning you will have to turn off SQL server from restricting you from re-building the table( this should be in the option menu, and the message that pops up when you try to rebuild the table will tell you exactly what what option to turn off) . I would suggest you turn it back on when you are done.

Also you will need to remove the insert to the primary key field as creating identity will turn off inserts into that column

You should create table with this syntax:

CREATE TABLE UXFaturas ( IDNumFaturas int IDENTITY (1, 1) PRIMARY KEY, );

Or

Getting maximum value of IDNumFaturas from current table UXFaturas and increase one value.

Eg If its 8 is last maximum value of IDNumFaturas means you should get that value and increase one values as 9.

Example query for getting maximum value of IDNumFaturas from UXFaturas table

SqlCommand cmd = new SqlCommand ("SELECT MAX (IDNumFaturas) +1 FROM UXFaturas", conn); int newID = (int)cmd.ExecuteScalar(); SQLcm.Parameters.AddWithValue("@idnumfaturas", newID);

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