简体   繁体   中英

How to write the query for auto-generated ID

I get an error when I input the drop down list parameter as data, I could not add the parameter data into the invoice table,the parameter data for subtotal, tax and total got their own value, but it only work well for manually input the data.

Drop down list parameter:

using (var cmd = con.CreateCommand())
{
cmd.CommandText = @"insert into Invoice(subtotal,tax,total) values (@subtotal,@tax,@total); select SCOPE_IDENTITY() as invoiceID;";
cmd.Parameters.AddWithValue("@subtotal", subtotal);
cmd.Parameters.AddWithValue("@tax", tax);
cmd.Parameters.AddWithValue("@total", total);
object OBJinvoiceID = cmd.ExecuteScalar();
}

Manually input:

using (var cmd = con.CreateCommand())
{
cmd.CommandText = @"insert into Invoice(subtotal,tax,total) values (2,2,2); select SCOPE_IDENTITY() as invoiceID;";
object OBJinvoiceID = cmd.ExecuteScalar();
}

Just remove the field from your values-listing:

insert into Invoice(subtotal,tax,total) values (@subtotal,@tax,@total); select SCOPE_IDENTITY() as invoiceID;

Also you can use the OUTPUT-Clause to get the value using:

into Invoice(subtotal,tax,total) OUTPUT invoiceID values (@subtotal,@tax,@total);

In the case you actually want to set the identity -column manually, you can use SET IDENTITY_INSERT as described here in MSDN

不要设置发票ID

insert into Invoice(subtotal,tax,total) values (@subtotal,@tax,@total);

If you have it Incrementing in database you dont need to Alter it again in the code. Just remove the invoiceID from your statement

I'm not a .NET guy, but by googling I think you have to not mention the identity field in your insert query:

using (var cmd = con.CreateCommand())
            {
                cmd.CommandText = @"insert into Invoice(subtotal,tax,total) values (@subtotal,@tax,@total);
// the rest
            }

Plz take a look in this simple tutorial: w3schools

insert into Invoice(subtotal,tax,total) values (@subtotal,@tax,@total); select SCOPE_IDENTITY() as invoiceID;

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