ASP.NET SQL Server insert error
So I've these two statements:
string insertUserData = "INSERT INTO W711_User_Data(Network_ID, F_Nam开发者_运维百科e, M_Name, L_NAME, Badge, Telephone, Org_Code, Org_Name, Req_Head_Network_ID)Values(@networkID1, @firstName1, @middleName1, @lastName1, @badgeNumber1, @telephone1, @orgCode1, @orgName1, @myUserName1)";
string insertReservationData = "INSERT INTO W711_Reservation_Data(ID, Network_ID, EventTitle, StartDate, EndDate, Justification) Values(null, @networkID2, @eventTitle1, @startDate1, @endDate1, @justification1)";
The network id in second string is foreign key relation with network id in first table.
The problem is: When I run the application
in VS2010
, it gives the error:
Can't insert explicit value for identity column
in table 'W711_Reservation_Data'
when IDENTITY_INSERT
is set to OFF
.
Then I read to do this somewhere:
SET IDENTITY_INSERT W711_Reservation_Data ON
But it also fails and gives the same error again! Please help Thanks p.s. sql server
if your id is an identity (aka auto generated from the database), just do not list the ID field in any place in the INSERT Statement, not as column name and not in the values list:
to get the ID generated by SQL Server you call SCOPE_IDENTITY in this way:
INSERT INTO W711_Reservation_Data(Network_ID, EventTitle, StartDate, EndDate, Justification) Values(@networkID2, @eventTitle1, @startDate1, @endDate1, @justification1)";
RETURN SCOPE_IDENTITY()
Edit: this is the second of your two statements, I have removed the ID and the NULL...
Why are you trying to insert null
as the value for the ID
column anyway? Assuming that this is the IDENTITY
column that is the source of the complaint then it seems more likely you need to just leave it out of the column list and don't pass any explicit value in. i.e.
INSERT INTO W711_Reservation_Data
(Network_ID, EventTitle, StartDate, EndDate, Justification)
Values
(@networkID2, @eventTitle1, @startDate1, @endDate1, @justification1)
There might be two possibility.
1] if Network_ID in first table is primary key auto generated then insert data in first table. then get latest network id from that table and pass that network id with second query.
2]. If ID column in second table is primary key then Do not pass null in second query. either make auto generated or pass uniquer value in query.
精彩评论