delete from two table having foreign key constraint - sql-server

I have two tables in my database and the t1 table primary key is uid, t2 table a foreign key name desg. now I want to delete or update this uid in one table give error that
Now row was updated. data in the row
was not committed. error
source:.netSqlclient data provider.
error message: the update statement
conflicted with the reference
constraint fk_t2_t1.the conflict occur
in the database DBname, dbo.t2,column
desg. the stsement has been
terminated.
and when I try to delete, it show this message.
executed SQl statement: delete from t1
where uid='abc'
error source:.netSqlclient data
provider. error message: the Delete
statement conflicted with the
reference constraint fk_t2_t1.the
conflict occur in the database DBname,
dbo.t2,column desg. the stsement has
been terminated.
Please tell me how to do this update and delete.
I am new to this field need help thanks in advances.

first delete the t2 table a foreign key then delete t1 table primary key is uid . this will work not vise versa

You have one or more child records in table t2 which are pointing at the master record in table t1 that you want to delete. Before you can delete your record in t1, you must delete the child records in t2.
For example:
(1) delete * from t2 where t2.desg = t1.uid;
(2) delete * from t1 where t1.uid = UID_TO_BE_REMOVED;
I would recommend reading a good reference on creating tables and performing queries for the SQL database you are using.
Good luck!

Related

SQL Server foreign key contsraint preventing insert, where no conflict exits

I have 2 tables, and I have just done an insert of about 1,000,000 rows. I turned off foreign key constraints , but I have an error when I try and reinstate them with
ALTER TABLE ForexRebatesNow.dbo.Transactions WITH CHECK CHECK CONSTRAINT ALL
I get the following error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Transactions_RebateAccounts". The conflict occurred in database "ForexRebatesNow", table "dbo.RebateAccounts", column 'Id'.
So I go to look for RebateAccountId that does not have a corresponding Id in the RebateAccounts table
SELECT Id
FROM ForexRebatesNow.dbo.RebateAccounts
WHERE Id NOT IN (SELECT RebateAccountId
FROM ForexRebatesNow.dbo.Transactions)
But this returns zero rows, so in my mind that conflict does not exist.
Am I missing something here?
EDIT
The relationship between RebateAccounts and Transactions is One to Many. RebateAccountId is a Nullable int on Transactions table as not allTransactions will have an associated RebateAccount, but any RebateAccount can have many Transactions
As you have not provided the relations between the two tables, I assume that there is a One-to-Many relation between RebateAccounts and Transactions Table. If I'm right then I guess you are checking the conflict in an opposite way. Your foreign key in in the dbo.Transactions table but you are checking it with the dbo.RebateAccounts table.
Try the following query to find the conflict.
SELECT * FROM Transactions WHERE RebateAccountId NOT IN (SELECT Id FROM RebateAccounts)
If any row shows up then that row has an account id that does not belong to any account. That's where your conflict is.
Hope it helps.

How to create connection between two tables in SQL Server 2008?

I have database that has Student table with information about each student in the system. Each record in that table has unique identifier that was created with NEWID() in SQL 2008. Then I have three other tables that use the same ID to link the student and the record. I'm wondering if I need to set any kind of property that will link these tables/records. Here is example of my Student table:
st_id -> Auto increment id
st_studentGUID -> Primary key
st_firstName
st_lastName
st_dob
st_gender
st_uid
st_udt
st_utime
And here is example of my other three tables:
Table 1 Table 2 Table 3
tb1_id -> auto increment tb2_id -> auto increment tb3_id -> auto increment
tb1_studentGUID tb2_studentGUID tb3_studentGUID
I have tried to create foreign key for each Table 1,2 and 3 on studentGUID but I got an error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Table1_Student". The conflict occurred in database "testDB", table "Student", column 'st_studentGUID'.
After I have done some research seems like this error occurred because Table 1 doesn't have all st_studentGUID. This make sense because student record might exist in Table 3 but not in Table 1. I'm wondering if there is any other sort of relation that I can set between the tables? Should I maybe use the Indexes on studentGUID fields? This is the reason why I'm asking this, in one of my update queries I use auto incremented id in where clause and for some reason I received an error that looks like this:
ErrorCode 1205
Message [Macromedia][SQLServer JDBC Driver][SQLServer]Transaction (Process ID 111) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
SQLState 40001
and error was pointing to the line that is end of the update query that looks like this:
<cfquery name="updateTable1" datasource="testDB">
UPDATE Table1
SET
tb1_testdt = <cfqueryparam value="#FORM.frm_testdt#" cfsqltype="cf_sql_date" maxlength="10" null="#yesNoFormat(!len(FORM.frmhs_testdtgr))#" />
FROM Table1 AS Table
LEFT OUTER JOIN studentLocked AS Locked
ON Locked.lk_studentGUID = Table.tb1_studentGUID
WHERE tb1_id = <cfqueryparam value="#FORM.frm_id#" cfsqltype="cf_sql_integer" />
AND lk_active = '1'
AND lk_staffID = <cfqueryparam value="#trim(appStaff)#" cfsqltype="cf_sql_char" maxlength="10" />
</cfquery>
Query above is checking if studentGUID exists in Lock table, reason why I'm doing this is because we do not want two different users updating the same record at the same time. Query updates single record and should be pretty fast. I'm confused whit the error message above deadlock victim. Is there something in my database design that is off or my update query is causing this error? I couldn't find anything on the web that could help me fix this issue. if anyone has experience with this kind of problem please let me know.
If all StudentGUIDs exist in the Student table, then the correct design is to have the StudentGUID in Table1, Table2 and Table3 be a Foreign Key to the Student table.
Now that you've sorted out your foreign key issue with the missing record from Student, try setting up your FKs on all of your tables, then re-try your update query.
If the deadlock issue persists and is reproducible, submit a new question for that, including the schema for the table you're updating and the values you're trying to pass.
Here's a script that demonstrates you can create the relationships you described provided all the keys are present in the students table:
CREATE TABLE students (st_id AS NEWID(),
st_studentGUID UNIQUEIDENTIFIER PRIMARY KEY)
INSERT INTO students (st_studentGUID) VALUES ('3B9F59DD-BF0A-4A09-BF4E-A396E2978B24')
INSERT INTO students (st_studentGUID) VALUES ('7CC5FF67-DAB8-426A-B9F7-E9F041718B6B')
INSERT INTO students (st_studentGUID) VALUES ('84B80D3E-44C4-4291-857D-B6CA6552369D')
CREATE TABLE t1 (tb1_id AS NEWID(), tb1_studentGUID UNIQUEIDENTIFIER)
ALTER TABLE t1
ADD CONSTRAINT FK_t1_tbl_studentGUID FOREIGN KEY (tb1_studentGUID) REFERENCES students(st_studentGUID)
INSERT INTO t1 (tb1_studentGUID) VALUES ('3B9F59DD-BF0A-4A09-BF4E-A396E2978B24')
CREATE TABLE t2 (tb2_id AS NEWID(), tb2_studentGUID UNIQUEIDENTIFIER)
ALTER TABLE t2
ADD CONSTRAINT FK_t2_tbl_studentGUID FOREIGN KEY (tb2_studentGUID) REFERENCES students(st_studentGUID)
INSERT INTO t2 (tb2_studentGUID) VALUES ('7CC5FF67-DAB8-426A-B9F7-E9F041718B6B')
CREATE TABLE t3 (tb3_id AS NEWID(), tb3_studentGUID UNIQUEIDENTIFIER)
ALTER TABLE t3
ADD CONSTRAINT FK_t3_tbl_studentGUID FOREIGN KEY (tb3_studentGUID) REFERENCES students(st_studentGUID)
INSERT INTO t3 (tb3_studentGUID) VALUES ('84B80D3E-44C4-4291-857D-B6CA6552369D')
Now create a 4th table, add a UUID that isn't in the students table, and try to create the foreign key constraint:
CREATE TABLE t4 (tb4_id AS NEWID(), tb4_studentGUID UNIQUEIDENTIFIER)
INSERT INTO t4 (tb4_studentGUID) VALUES ('897925F1-BE92-44EB-82C3-88E1C33C7792')
ALTER TABLE t4
ADD CONSTRAINT FK_t4_tbl_studentGUID FOREIGN KEY (tb4_studentGUID) REFERENCES students(st_studentGUID)
Which reproduces your error message:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_t4_tbl_studentGUID". The conflict occurred in database "IconERP", table "dbo.students", column 'st_studentGUID'.

Delete, Insert, Update using table from cache?

I have a stored procedure which runs a couple of deletes, inserts and updates for several tables.
My problem: The procedure causes key constraint violations.
Example:
DELETE FROM tableA WHERE key='1'
DELETE FROM tableB WHERE key='1'
Table B has a foreign key reference to table A, the procedure stops and I get an error message. All changes are discarded.
My question: How can I tell the procedure or server that the entry in table A is already deleted? Can I use table A from the cache for the foreign key reference comparisons?
I use a microsoft sql server.
EDIT
I'm sorry, I mixed the chronological order.
In fact, table A has the FK and its entry is the first one to be deleted.
Table B follows afterwards with no reference to table A.
Nevertheless, I get a "conflicted with the REFERENCE constraint" message.
The only explanation for this error message I have is, that the delete on table A is not committed.
EDIT
I may have found the problem. All my delete statements are enclosed in BEGIN/END.
So I have:
BEGIN
DELETE FROM tableA WHERE key='1'
DELETE FROM tableB WHERE key='1'
END
As far as I understand, such enclosed statements are run as one big statement before anything is committed.
Regards
You have two options:
To perform queries in the correct so the server will be able to execute them correctly.
You can get rid of foreign keys for those tables during the execution of the procedure.
If TABLEB has a FK from TABLEA then you must first delete fromTABLEB:
DELETE FROM tableB WHERE key='1' --Doing this will remove the row that references TABLEA
DELETE FROM tableA WHERE key='1' --TABLEA can be deleted because there are no references to the row in the other TABLE

How to delete record in Parent table without affecting the Child table?

I have 2 tables in my database, Table A and Table B.
Table A is a Master table and table B is a Transaction table. Table B have Foreign Key (IdTableA)
Example :
I already have a record in table B with IdTableA in it.
INSERT INTO Table_B VALUES (IdTableB, IdTableA, 500000);
and when I tried to delete record in Table A which is IdTableA there is an error.
I want to delete a record in Table A without affecting record in Table B
what should i do ? is it possible ?
You didn't post the error message, but most likely the IdTableA column is a foreign key to Table A. That means a row in Table A can't be deleted if any row in Table B references that row. There is no way to get around this except to permanently remove the foreign key.
The purpose of a foreign key is to prevent exactly this scenario. It prevents data integrity problems where rows would otherwise make no logical sense because other rows they reference do not actually exist.
http://en.wikipedia.org/wiki/Foreign_key

foreign key data deletion should display error for primary key

i have two tables Table1 and Table2. Where table1 column primary key is referred to table2 column as foreign key.
Now i have to display a error message of constraint violation when ever i delete records from table2 which is having foreign key column of table1.
If I get it right your column A (say) in table 1 references column B (say) in table 2.
What you can do is set the ON DELETE to NO ACTION which will prevent deletion of records from table 2 if any children of it still exists in table 1.
You can can do this by:
ALTER TABLE TABLE1 ADD FOREIGN KEY (A) REFERENCES TABLE2 (B) ON DELETE NO ACTION;
You don't have a constraint violation if you delete records from the child table and not the parent. It is normal to delete child records. For instance if I have a user table and a photos tables that contains the userid from the users table, why would I want to stop that action and throw an error if I want to delete a photo? Deleting a child record doesn't also delete the parent.
If you really want to do that, then you must do it through a trigger (make sure to handle multiple record deletes) or if the FK is a required field, then simply don't grant permissions to delete to the table. Be aware that this may mean you can never delete any records even when you try to delete. A simple method may be to not have a delete function available in the application.
I suspect what you really need to a to get a better definition of what is needed in the requirements document. In over 30 years of dealing with hundreds of databases, I have never seen anyone need this functionality.

Resources