简体   繁体   中英

error with Scope_Identity when trying to insert in C#

 string cmdTrainText = "INSERT INTO dbo.Event_Train(SCOPE_IDENTITY(), Train," + 
                                "Barrel_Train, Fire_Truck, Tram, Beverage_Cart) " + 
                        "VALUES(cbTrain, cbTBarrelTrain, cbTFire_Truck, cbTram, " +
                               "cbTBeverage_Cart)";

I am getting the following error

System.DataSqlClient.SqlException {"Incorrect syntax near '('."}

Everything compiles OK. I get this error when I run the Program. I am using Visual Studio 2015. I am trying to learn C#

Do I need to put something around SCOPE_IDENTITY() ?

ScopeIdentity should be the first element inside the VALUES brackets and you then you have to write the column name instead at the first brackets! ScopeIdentity in this case seems to be a value and not a column name for me.

An edit would look like this (with proposed column name ScopeID ):

string cmdTrainText = "INSERT INTO dbo.Event_Train(ScopeID, Train," + 
                              "Barrel_Train, Fire_Truck, Tram, Beverage_Cart) " + 
                      "VALUES(SCOPE_IDENTITY(), cbTrain, cbTBarrelTrain, cbTFire_Truck, " +
                              "cbTram, cbTBeverage_Cart)";

You cannot have a different number of values vs. number of fields; you have 6 fields and only 5 values. Furthermore, if you have an IDENTITY field the db will autoincrement it without your specifying a value for it. The SCOPE_IDENTITY is a return value to provide the last IDENTITY value generated by the db for your insert and for the scope of the action (read up on IDENTITY vs. SCOPE_IDENTITY ).

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