Foreign Key fails to create - sql-server

I want a foreign key between 2 tables , so i try it like i always do. Now the issue i'm having is he fails to create , and by the looks of it it fails to create because there is already a key but there isnt.
- Unable to create relationship
'FK_tbl_Paramed_RegistratieBehandelingen_Users'.
The ALTER TABLE statement conflicted with the
FOREIGN KEY constraint "FK_tbl_Paramed_RegistratieBehandelingen_Users".
The conflict occurred in database "Nestor_Server",
table "dbo.Users", column 'UserID'.
Ive checked if they have the same type , they do(bigint) so don't get why he won't create it

It is possible that you have records in RegistratieBehandelingen(Not sure about the table name) which is not present in Users Table.
select * from RegistratieBehandelingen a where UserID IS NULL or
not exists (select 1 from Users b where b.UserID= a.UserID)

This means that you have child data with no matching parent ID.
Run the following to see if you get any results:
SELECT *
FROM tbl_Paramed_RegistratieBehandelingen r
LEFT JOIN Users u on r.UserID = u.UserID
WHERE u.UserID IS NULL
(changing table and column names where appropriate)
If you get any results then it should show which records contains UserIDs that don't match to Users.

After the above query, you may want to delete non existing UserId from table tbl_Paramed_RegistratieBehandelingen or insert them in table Users .

Related

OUTPUTting fields from an INSERT...SELECT query using fields from the SELECT results

I'm trying to populate an association table with the output from an INSERT...SELECT query in Microsoft SQL Server, but I'm getting errors and can't find a workaround.
This is the most minimal, reproducible problem I can come up with: I have a table of things defined as:
CREATE TABLE dbo.things(
id int IDENTITY(1, 1) NOT NULL PRIMARY KEY,
name nvarchar(20) NOT NULL UNIQUE
);
that is already populated. To allow the example to work, use this:
INSERT INTO dbo.things(
name
)
VALUES('Thing1'),('Thing2'),('Thing3');
Now I have a table of widgets:
CREATE TABLE dbo.widgets(
id int IDENTITY(1, 1) NOT NULL PRIMARY KEY,
description nvarchar(255) NULL
);
and a further table that associates things and widgets in a many-to-many manner:
CREATE TABLE dbo.thing_widget_associations(
thing_id int NOT NULL REFERENCES dbo.things(id),
widget_id int NOT NULL REFERENCES dbo.widgets(id),
PRIMARY KEY(
thing_id,
widget_id
)
);
However, each thing needs to have at least one widget association, but some of the necessary widgets are missing, so I'd like to create them, then associate them with the corresponding thing all in the same query.
Here's what I tried:
INSERT INTO dbo.widgets(
description
)
OUTPUT
INSERTED.id, -- Identifier of the newly created widget.
t.id -- Identify of the associated thing. <- Doesn't work. I get error here.
INTO dbo.thing_widget_associations(
widget_id,
thing_id
)
SELECT
'Default widget for thing ' + t.name
FROM dbo.thing_widget_associations AS twa
RIGHT JOIN dbo.things AS t
ON twa.thing_id = t.id
WHERE twa.thing_id IS NULL;
However, when I try to run this query, I get the following:
Msg 4104, Level 16, State 1, Line 6
The multi-part identifier "t.id" could not be bound.
Msg 332, Level 16, State 1, Line 1
The target table 'dbo.thing_widget_associations' of the OUTPUT INTO clause cannot be on either side of a (primary key, foreign key) relationship. Found reference constraint 'FK__thing_wid__thing__5165187F'.
From what I've seen, it doesn't seem possible to use a field from a table queried as part of the INSERT query in the OUTPUT clause, and I think that's what the first error refers to. However, if I omit the OUTPUT clause, then I can't associate each created widget with the thing used to create it.
Can anyone also explain the second error, which has completely passed me by? Is that a consequence of the first error?
Bottom line: is there a way to do this? If so, what am I missing?
According to the documentation, the output of an insert can refer to just the inserted and deleted tables. Using merge is the workaround.
Here is how to restructure with merge
merge dbo.widgets t
using (
select 'Default widget for thing ' + t.name w, t.id
from dbo.things as t
left join dbo.thing_widget_associations twa on twa.thing_id = t.id
where twa.thing_id is null
)s on 1=0
when not matched then
insert (description) values (s.w)
output INSERTED.id, s.id
into dbo.thing_widget_associations(widget_id, thing_id);
note that with the sample table's constraints, this generates an error The target table 'dbo.thing_widget_associations' of the OUTPUT INTO clause cannot be on either side of a (primary key, foreign key) relationship. Found reference constraint 'FK__thing_wid__thing__2BFE89A6'.
Therefore I've tested without these present on the table.

Delete a row in a table triggers a deletion in an other table

I have a strange issue. When a deletion is performed in a table I got a deletion in another table!
I executed this command to search for all triggers in the database, but I didn't find any.
select * from ALL_TRIGGERS;
How can I investigate this issue?
Maybe there is a foreign key constraint between the two tables? If so, is it defined as ON DELETE CASCADE?
This query will find foreign keys referencing a primary or unique key on YOUR_TABLE_NAME (which is the table you targeted with your delete).
select r.table_name
, r.constraint_name as foreign_key
, r.delete_rule
from all_constraints r
join all_constraints p
on p.owner = r.r_owner and p.constraint_name = r.r_constraint_name
where r.constraint_type = 'R'
and p.constraint_type in ('U', 'P')
and p.table_name = 'YOUR_TABLE_NAME'
/
The DELETE_RULE will show you whether the deletion of a parent record is cascaded to the dependent records.

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'.

Dependency in SQL

In SQL, I've to delete a data from table A which is dependent on table B.
The data to be deleted should satisfy two conditions WorkArea='123' and FileNo='45'.
Table B has WorkArea but it does not contain data for FileNo.
And Table A contains the record satisfying both the conditions.
There isn't any reference key. For more clarity, adding a query here:
Select * from table A where WorkArea='123' and FileNo='45';
This will generate the resulting record. But as it is dependent on Table B, I cannot delete it directly. Also, to delete it from table B isn't possible because data in WorkArea is a whole and it contains many files and I have to delete a specific File.
So how can I delete data from table A?
This is Table A with col1 and col2 as primary key.
This is Table B with col1 as a primary key.
If you have no Foreign Keys, the following sentence will work.
DELETE FROM [A] WHERE [WorkArea] = '123' AND [FileNo] = '45';
Then you can programmaticaly check if there are "orphans" on table B with the following request :
SELECT DISTINCT [B].[WorkArea]
FROM [B]
LEFT JOIN [A]
ON [A].[WorkArea] = [B].[WorkArea]
WHERE [A].[WorkArea] IS NULL
To enhance this last part and produce a DELETE sentence from it, just store the result of this request into a temporary table then use it as a WHERE statement with the IN keyword.

Error when link 2 table in sql server

I am trying to link 2 table in sql server let's assume one of them called customer and the other is product.
customer has custID as primary key and i want to link it with custID in product table as foreign key, and its give me this error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_product_customer". The conflict occurred in database "xyz", table "dbo.customer", column 'custID #'.
Is there anyone know, how can I fix the issue?
This could have many reasons.
Do you have a type missmatch between those columns?
Is every customer in products also in your customer table?
You can check the second part by using this:
SELECT DISTINCT p.customer_id
FROM products as p
LEFT JOIN customers as c ON p.customer_id = c.customer_id
WHERE c.customer_id is null
Hope this give you a hint.

Resources