How to alter relationship in MS SQL 2008? - sql

I created a MS SQL Server 2008 R2 Database and I created a relationship between tables using Foreign Keys, I have (Devices) table and (Users) table and the relationship is one to many (1 - ) (one device can have many users), but I want to change this to be many to one ( - 1) (one user can have many devices) how to do that using T-SQL or using relationships design window?
Regards

1) Delete your foreign key constraint on the users table
ALTER TABLE User
DROP CONSTRAINT FK_User_Device;
2) Delete the device_id column from users
ALTER TABLE users DROP COLUMN device_id;
3) Add user_id column to device
ALTER TABLE device ADD user_id YOURIDDATATYPE;
4) Create foreign key constraint for user_id in device
ADD CONSTRAINT FK_UserID_Device FOREIGN KEY (user_id)
REFERENCES User (id) ;
Replace column names / data types with your data types.

If it is many to one what you wanted (means one user many devices but one device only one user) then you can add one more column in device table refering to user table...
as what you have done for one to many relationship...
but revert of this

Related

How to insert into a table if it violates a foreign key constraint

I am working on a script that moves data between two databases.
I am moving a table of Phone Numbers. Each Phone Number is for a user.
The problem is that each Phone Number entry references a User with a User ID. Some of these users do not exist anymore, so when I try to insert, it returns a foreign key constraint violation.
insert or update on table "phone_numbers" violates foreign key constraint "fk3843uenfej83jf32wde"
user_id = 10 is not present in table users
However, I can't go and delete each single user reference as there are thousands of references.
So what would be the best way to approach it?
Should I simply remove the foreign key constraint?
Phone numbers that belong to non existent users are termed “orphaned” data.
Either clean up orphaned data in the source data (orphaned data shouldn’t exist):
delete from phone_number
where not exists (select * from user where id = user_id)
Or don’t select them when exporting:
select p.*
from phone_number p
join user u on u.id = p.user_id
I would not remove the constraint, as it can have impacts on other things (application ? report ? Whatever).
So the question is wHhat do you need ?
Insert all ph. numbers including the ones without users
Insert only ph. numbers with users associated
In any case load your data to a 'temp' table call, temp_phones, without any constraint.
In case 1 migrate data to phone_numbers making userid = null if the user is not present anymore. You can do it with an "easy" query
In case 2 migrate data to phone_numbers only when the userid of the record is found in your user table, also this can be done with a query
You can perform both processes also after having migrate the data. In this case you should disable\remove the constraint, update the userid according to the proposed rules, then recreate the constraint

Guarantee that multiple FK fields belongs to the same row in another table

On a SaS project (Software as a Service), imagine this scenario:
The main table for customers, those who use the application, is tenant and it primary key is the column id.
I have 3 tables to manage data from tenants and one specific table to manage a functionality of vacancies:
Period, Unity and Shift all those with PK id and FK tenant_id.
My table vacancy have 3 Foreign Keys
period_id - References to "Period" table
unity_id - References to "Unity" table
shift_id - References to "Shift" table
Now the problem:
I need to guarantee that all these 3 FK's are reference to rows on Period, Unity and Shift tables that belong to the same Customer on the tenant table.
I was clear in my explanation?
Maybe i can create a Trigger to handle those validations. I really don't know if SGBD already have resources to do with that.
For information: I'm using SQL Server with Eloquent ORM. But, if really exists a solution for this, the best would be one that who works everywhere.
1) Ensure that your tenant_id is defined as NOT NULL on the tables Period, Unity and Shift.
2) Create the following unique keys on that tables:
Period(tenant_id, period_id)
Unity(tenant_id, unity_id)
Shift(tenant_id, shift_id)
3) Define column tenant_id for table vacancy as NOT NULL.
4) Define the folowing FKs on table vacancy:
(tenant_id, period_id) referencing Period(tenant_id, period_id)
(tenant_id, unity_id) referencing Unity(tenant_id, unity_id)
(tenant_id, shift_id) referencing Shift(tenant_id, shift_id)
This way you can guarantee that every linked row has the same tenant_id.

What would be the best way to link these two tables

I have two tables in a database, both of which are derived from official government reference tables originally supplied in spreadsheet form.
The structure of these two tables are illustrated below.
Table 1 (Species Codes)
Table 2 (Allowed presentation codes)
When I try and create a relationship between the first and the second (so as to make full use of the ability to look up values in the second table I get the following error when trying to link speciescodes.FAOCode to allowedstates.ErsSpeciesCodes).
'SpeciesCodeLookup' table saved successfully
'AllowedPresentationAndStateCodesLookup' table
- Unable to create relationship 'FK_AllowedPresentationAndStateCodesLookup_SpeciesCodeLookup'.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_AllowedPresentationAndStateCodesLookup_SpeciesCodeLookup". The conflict occurred in database "FishTrackerPro", table "dbo.SpeciesCodeLookup", column 'FAOCode'.
Can anyone enlighten me as to
1) why is this error occurring
2) is there a way (by altering one or other table where such a relation might be established?
It seems you are getting this issue because referential integrity is not met. I.e Foreign key table must not have values which does not exists in primary key table.
Check these links :
Alter table conflicted with foreign key constraint
SQL conflicted with the FOREIGN KEY constraint

SQL delete query with foreign key constraint

I know that this question belongs to the very early stages of the database theory, but I have not encountered such a problem since several months. If someone has a database with some tables associated together as "chain" with foreign keys and they want to delete a record from a table which has some "dependent" tables, what obstacles arise? In particular, in a database with tables: Person, Profile, Preference, Filter exist the associations as Person.id is foreign key in Profile and Profile.id is foreign key in Preference and Filter.id is foreign key in Preference, so as that all the associationsenter code here are OneToMany. Is it possible to delete a Person with a simple query:
Delete from Person p where p.id= 34;
If no, how should look like the query in order to perform the delete successfully?
If the database in the application is managed by hibernate, what constraints (annotations) should I apply to the associated fields of each entity, so as to be able with the above simple query to perform the delete?
FOR SQL VERSION
Look at the Screenshot. you can use the Insert Update Specificaiton Rules. as it has Delete and Update Rules. you can set either of these values.
Foreign key constraints may be created by referencing a primary or unique key. Foreign key constraints ensure the relational integrity of data in associated tables. A foreign key value may be NULL and indicates a particular record has no parent record. But if a value exists, then it is bound to have an associated value in a parent table. When applying update or delete operations on parent tables there may be different requirements about the effect on associated values in child tables. There are four available options in SQL Server 2005 and 2008 as follows:
No Action
Cascade
SET NULL
SET Default
Use this article for Refrence.
http://www.mssqltips.com/sqlservertip/2365/sql-server-foreign-key-update-and-delete-rules/
ORACLE VERSION
you can use one of below.
alter table sample1
add foreign key (col1)
references
sample (col2)
on delete no action;
alter table sample1
add foreign key (col1)
references
sample (col2)
on delete restrict;
alter table sample1
add foreign key (col1)
references sample (col2)
on delete cascade;
for refrance.
http://docs.oracle.com/cd/B19306_01/server.102/b14200/clauses002.htm
answer is no if there is foreign key constraint then you have to delete leaf node table data first
that is first delete from Preference table
then from Profile and Filter Table
then delete record from Person table
This is the generic concept that you apply anywhere

Create a one to many relationship using SQL Server

How do you create a one to many relationship using SQL Server?
Define two tables (example A and B), with their own primary key
Define a column in Table A as having a Foreign key relationship based on the primary key of Table B
This means that Table A can have one or more records relating to a single record in Table B.
If you already have the tables in place, use the ALTER TABLE statement to create the foreign key constraint:
ALTER TABLE A ADD CONSTRAINT fk_b FOREIGN KEY (b_id) references b(id)
fk_b: Name of the foreign key constraint, must be unique to the database
b_id: Name of column in Table A you are creating the foreign key relationship on
b: Name of table, in this case b
id: Name of column in Table B
This is a simple example of a classic Order example. Each Customer can have multiple Orders, and each Order can consist of multiple OrderLines.
You create a relation by adding a foreign key column. Each Order record has a CustomerID in it, that points to the ID of the Customer. Similarly, each OrderLine has an OrderID value. This is how the database diagram looks:
In this diagram, there are actual foreign key constraints. They are optional, but they ensure integrity of your data. Also, they make the structure of your database clearer to anyone using it.
I assume you know how to create the tables themselves. Then you just need to define the relationships between them. You can of course define constraints in T-SQL (as posted by several people), but they're also easily added using the designer. Using SQL Management Studio, you can right-click the Order table, click Design (I think it may be called Edit under 2005). Then anywhere in the window that opens right-click and select Relationships.
You will get another dialog, on the right there should be a grid view. One of the first lines reads "Tables and Columns Specification". Click that line, then click again on the little [...] button that appears on the right. You will get this dialog:
The Order table should already be selected on the right. Select the Customer table on the left dropdown. Then in the left grid, select the ID column. In the right grid, select the CustomerID column. Close the dialog, and the next. Press Ctrl+S to save.
Having this constraint will ensure that no Order records can exist without an accompanying Customer record.
To effectively query a database like this, you might want to read up on JOINs.
This is how I usually do it (sql server).
Create Table Master (
MasterID int identity(1,1) primary key,
Stuff varchar(10)
)
GO
Create Table Detail (
DetailID int identity(1,1) primary key,
MasterID int references Master, --use 'references'
Stuff varchar(10))
GO
Insert into Master values('value')
--(1 row(s) affected)
GO
Insert into Detail values (1, 'Value1') -- Works
--(1 row(s) affected)
insert into Detail values (2, 'Value2') -- Fails
--Msg 547, Level 16, State 0, Line 2
--The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Detail__MasterID__0C70CFB4".
--The conflict occurred in database "Play", table "dbo.Master", column 'MasterID'.
--The statement has been terminated.
As you can see the second insert into the detail fails because of the foreign key.
Here's a good weblink that shows various syntax for defining FK during table creation or after.
http://www.1keydata.com/sql/sql-foreign-key.html
If you are not using SSMS then here is the syntax:
ALTER TABLE <table_name>
ADD <constraint_name> FOREIGN KEY
(<column_name1> ,
<column_name2> )
REFERENCES <table_name>
(<column_name1> ,
<column_name2>)
http://infogoal.com/sql/sql-add-foreignkey.htm
If you are talking about two kinds of enitities, say teachers and students, you would create two tables for each and a third one to store the relationship. This third table can have two columns, say teacherID and StudentId.
If this is not what you are looking for, please elaborate your question.