i'm trying to update my data in datagridview by going to sqldatasource properties "update queries" and writing the codes but its showing an error message
"Violation of PRIMARY KEY constraint 'PK_contact_master'. Cannot insert duplicate key in object 'dbo.admission_table'.
The statement has been terminated. "
plz tell me the exact code of editing the data in datagridview and update it..
Thanks,
Churchill
UPDATE:
Sql Code:
Update admission_table
set registration_id=#registration_id,
name_of_degree=#name_of_degree,
fees_paid=#fees_paid,
hostel=#hostel,
hostel_fees=#hostel_fees,
name_of_student=#name_of_student,
Date_of_birth=#Date_of_birth,
nationality=#nationality,
gender=#gender,
address=#address,
phone_no=#phone_no,
e_mail=#e_mail,
date=#date
Based on the sql query you provided it seems like your issue is that you don't have a where clause on your update query and you appear to be setting the primary key in the update.
This means you will update every record in the table with the same info and violate the PK.
To fix this I would first add a where clause. Once you are updating only the record you want you can most likely remove the registration_id from your set clause (assuming that's your pk).
Related
I'm trying to insert a record in database from a winform it was working fine and insert first 5 records with no error but when i try to insert next record it give me the error of Violation of PRIMARY KEY....!
The table is
But in Database table there is not record of no 6.
There is no trigger associate to this table.
there is no F-Key relationship of that table.
I tried it from sql server to insert it but again error.
What is the reason behind it?
There is definitely something wrong with your data. Please make sure you don't have a "duplicated PK" inserted.
And in my opinion, the PK should be generated automatically unless you have some special requirements.
You can fix this error by not trying to insert rows with a duplicate primary key.
Primary key should be auto generated.if you are getting this error then check your data first.
Primary key musty be inserted in table by itself, as this also reduces the code error chances that sometimes we try to insert same key again and again, (which is not the property of PK).
Also in database:
table> design> Primary Key> Properties>Identity specification> Yes
This will enable self insertion of key, also you can specify start index.
I am using LINQ-to-SQL class. I am inserting a new row using LINQ method object.InsertOnSubmit().
I need to set same value which is generate by SQL Server (using Identity) for table primary key column.
Now I need the same value at the time of inserting new row into table. And set the same value for other column in the same table at the time of insert only.
As I cannot update as after inserting because table has UPDATE TRIGGER.
I tried the following
_db.EmpNews.InsertOnSubmit(_EmpNews);
...
_db.DisplaySeq = _EmpNews.ID;
...
_db.SubmitChanges();
Where ID is the auto-generated (Identity) column.
The first question really is: why would you need to store the same value in two separate columns in the same table? What do you need this for? Doesn't seem to make a lot of sense to me....
Since the value of the IDENTITY column is only available once the row has actually been inserted, there is no way to get that value and set it to another column before the row has indeed been saved to the database table.
That basically leaves three options to get that value and store it somewhere else:
you can write an AFTER INSERT trigger that just set the other column to the value that's just been inserted in the IDENTITY column
you could wrap the whole saving process into a stored procedure which you call from your C# code (instead of just saving the object) and you would do the INSERT of the row, then get the newly created IDENTITY value and update the row again with that new value. But that would cause an UPDATE to happen - which you seem to say is impossible for you because of an UPDATE trigger (not quite clear on why this should be a problem....)
you can write two lines of C# code to get the IDENTITY value after it's been inserted (and available in the ID property of your object) and then store the object a second time. But that, too, would cause an UPDATE to happen - which you seem to say is impossible for you because of an UPDATE trigger (not quite clear on why this should be a problem....)
So I guess your best option would be an INSERT trigger to do this.
Try something like this:
CREATE TRIGGER trInsertEmpNews
ON dbo.EmpNews AFTER INSERT
AS BEGIN
UPDATE dbo.EmpNews
SET DisplaySeq = i.ID
FROM INSERTED i
WHERE dbo.EmpNews.ID = i.ID
END
I'm imagining that this is a simple question, but I'm running into syntax issues I think.
I have a table that has an event ID as primary key(eventID), a device ID that of what triggered the event, and a timestamp of when the event triggered. I"m processing the mySQL(5.1) elements via C# and command line.
My dilemma is that I have to duplicate/import the database to another database and I am getting duplicate entries due to the eventID being the primary key and it being updated everytime a new record is added automatically. Changing that isn't an option. So what I want to do is only insert into the database if my current deviceID+timestamp combination doesn't already exist.
I've found a lot of query examples, but they either throw syntax issues or simply don't work as needed. In pseudo code this is what I'm looking for..
IF timestampToInsert EXISTS WHERE deviceIDtoInsert ALSO EXISTS ON SAME ROW
UPDATE ROW
ELSE
INSERT INTO myTABLE (deviceID, timeStamp) VALUES (deviceIDtoInsert, timestampToInsert)
It sounds like you want to do an "upsert".
In MySQL this is called "INSERT...ON DUPLICATE KEY UPDATE":
INSERT INTO myTABLE (deviceID, timeStamp)
VALUES (deviceIDtoInsert, timestampToInsert)
ON DUPLICATE KEY UPDATE ...
Note this will only work if you have a unique index on (deviceID,timestamp)
I'm using Linq to SQL for the Database operations, and am trying to perform insert operations in a VIEW, It throws the Error,
XXt threw exception: System.InvalidOperationException: Can't perform Create,
Update or Delete operations on 'Table(XXX)' because it has no primary key.
How to use LINQ to insert a record into View using C#?
Thanks.
You can insert/update into views as per Updatable Views here. Only one underlying table can be inserted/updated to or it will fail. To implement this functionality using LINQ, do the following;
In your .DBML file tag one (or more) of the columns in the view as a Primary Key
Ensure any mappings in the view you are expecting to insert/update are exposed simply as a link to the base table column. Example;
Insertable/Updatable columns cannot include;
SUM(BaseTable.ColumnName) as ColumnName
ISNULL(BaseTable.ColumName,0) as ColumnName
BaseTable.ColumnName1 + ' ' + BaseTable.ColumnName2 as ColumnName
But can include;
BaseTable.ColumnName
BaseTable.ColumnName as MyNewName
Tag any of the columns that are not direct mappings to the base table as Auto Generated Value in your .DBML.
Give it a shot. I am successfully using this technique to use views as the only objects i use for both reading/inserting/updating records.
Actually you can insert into a view..if the underlying view has one table then you can insert into it.
If it has more than one table..then u can use instead of triggers;
Also I have inserted a record into a view..in linq to sql. (i have just started learning linq myself).
I had to create a primary key on a view. using the designer and then set the auto sync for that field to never. that should do the trick..
We can do insert, update and delete operations using a VIEW in LINQ to SQL process. All that we need to ensure is: view should have primary key.
We can set primarykey for a field in the view.
open the .dbml file designer and select the field which you want to make as primarykey and press F4 (open properties window).
select true for Primary Key property of the selected field.
Now execute your program. It should work.
You cannot insert into a VIEW. You can only insert into a table.
You can do this - see below.
Auto-Sync must be 'OnInsert' for this field in dbml.
I assume you mean that instead of trying to insert a row into a View, you are trying to insert a row into a table. You do not insert rows into Views.
Having said that, L2S requires your tables to have primary keys, as the error message indicates. Once you create a primary key, and update your .DBML accordingly, you should be fine.
Randy
I'm using ADO.NET with a strongly typed dataset in C# (.NET 3.5). I want to insert a new row to two tables which are related in an 1:n relation.
The table Attachments holds the primary key part of the relation and the table LicenseAttachments holds the foreign key part.
AttachmentsDataSet.InvoiceRow invoice; // Set to a valid row, also referenced in InvoiceAttachments
AttachmentsDataSet.AttachmentsRow attachment;
attachment = attachmentsDataSet.Attachments.AddAttachmentsRow("Name", "Description");
attachmentsDataSet.InvoiceAttachments.AddInvoiceAttachmentsRow(invoice, attachment);
Of course when I first update the InvoicesAttachments table, I'll get a foreign key violation from the SQL server, so I tried updating the Attachments table first, which will create the rows, but will remove the attachment association in the InvoiceAttachments table. Why?
How do I solve this problem?
On the relation between the tables, ensure that the "Both Relation and Foreign Key Constraint" is selected and "Update Rule" is set to "Cascade". Combined with the "Refresh the data table" option on the adapter, after you insert your parent row, the updated ID will "Cascade" down the relationships, preventing foreign key violations in your dataset. Your child tables will then be ready to properly insert into the database.
Some things to try:
When you configure the tableadapter, did you click on advanced options, and check on "refresh data table" so that it will retrieve the identity column value?
For me sometimes I either forgot to check it, or it didn't save the configuration correctly because I didn't have my table identity increment/seed set for whatever reason. Are you using identity increment on the table?
You might also consider just re-creating the adapters for those two tables.
Usually when I go back over everything I find it was something stupid on my part.
Lastly, you might consider calling update on the Primary table, then manually grab the primary key value and manually set the value when you insert the child record. If that doesn't make sense let me know and I will post code.
You need to tell your parent table's table-adapter to refresh the
data-table after update operation.
This is how you can do that.
Open the properties of ProgramUserGroupTableAdapter -> Default Select Query -> Advnaced options. and Check the option of Refresh the data table. Save the adapter now. Now when you call update on table-adapter, the data-table will be updated [refreshed] after the update operation and will reflect the latest values from database table. if the primary-key or any coloumn is set to auto-increment, the data-table will have those latest value post recent update.
Now you can Call the update as pug.Update(dsUserGroup.ProgramUserGroup);
Read latest values from the ProgramUserGroup coloumns and assign respective values into the child table before update. This will work exactly the way you want.
alt text http://ruchitsurati.net/files/tds1.png