SQL Server : multi CASCADE Operation - sql-server-2012

I have two tables, and I want HEDE2 columns as FOREIGN KEY REFERENCES by HEDE table. FOR creating second table it will not allow because its having warning:
More than one key specified in column level FOREIGN KEY constraint, table 'HEDE2'.
But when I tried to ALTER TABLE HEDE2 for FOREIGN KEY it allows me to do that. Is anybody knows WHY this happens. Is this a bug?
CREATE TABLE cascde.HEDE
(
HedeID INT,
HedeID2 INT,
HedeID3 INT
CONSTRAINT PK_HEDE
PRIMARY KEY (HedeID, HedeID2, HedeID3)
)
GO
CREATE TABLE HEDE2
(
Hede2ID INT PRIMARY KEY IDENTITY(1,1) ,
HedeID INT,
HedeID2 INT,
HedeID3 INT
CONSTRAINT FK_HedeID
FOREIGN KEY (HedeID, Hede2ID, HedeID3)
REFERENCES cascde.HEDE (HedeID, HedeID2, HedeID3)
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
Altering table HEDE 2 for foreign key. This allows me to do that:
ALTER TABLE cascde.HEDE2
ADD CONSTRAINT FK_HEDE
FOREIGN KEY(HedeID, HedeID2, HedeID3)
REFERENCES cascde.HEDE (HedeID, HedeID2, HedeID3)
ON UPDATE NO ACTION
ON DELETE NO ACTION
GO

You're missing a comma (,) after HedeID3 INT in the CREATE TABLE version.

Related

Alter Foreign Key Constraint Primary Key Error

I'm trying to drop and recreate a foreign key constraint, but I get an error
There are no primary or candidate keys in the referenced table 'inventory' that match the referencing column list in the foreign key 'fkInventory_VendorsInventory'.
I have already gone into the table design for both tables referenced in the code, and ensured that the column being referenced is a primary key.
ALTER TABLE inventory_vendors
DROP CONSTRAINT fkInventory_VendorsInventory;
ALTER TABLE inventory_vendors
ADD CONSTRAINT fkInventory_VendorsInventory
FOREIGN KEY(itemnum) REFERENCES inventory(itemnum)
ON UPDATE CASCADE
ON DELETE CASCADE
I have done such a drop and recreation before with no problems at all with another set of tables (unfortunately i don't remember which tables they were).
As you mentioned in comments, you have 2 primary key columns in the Inventory table:
one is itemnum, the other is store_id
I prepare a sample SQL here: 2 tables created
CREATE TABLE inventory
(
itemnum INT,
store_id INT,
inventoryDesc char(200),
primary key (itemnum, store_id)
);
CREATE TABLE inventory_vendors
(
inventory_vendors int,
itemnum INT,
store_id INT,
VendorDetails varchar(200),
primary key (inventory_vendors)
);
Create Unique constraint for one of the primary key. Here I am creating UNIQUE constraint for itemnum column
ALTER TABLE inventory
ADD CONSTRAINT [IX_inventory] UNIQUE ( [itemnum] )
GO
Then execute your script for creating the foreign key constraint on inventory_vendors for itemnum column and you can drop them as well.
ALTER TABLE inventory_vendors
ADD CONSTRAINT fk_Inventory_Vendors_Inventory
FOREIGN KEY(itemnum) REFERENCES inventory(itemnum)
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE inventory_vendors
DROP CONSTRAINT fk_Inventory_Vendors_Inventory;
Hope this might help you..

How do I change a column I created a while ago in sql to foreign key

I need to change multiple tables to foreign keys. I have used the command
ALTER TABLE financial_transactions
ADD FOREIGN KEY (item_rental_id) REFERENCES transaction_id(item_rental_id);
The table name was financial_transactions and the column name was item_rental_id. It gives me an error saying:
Foreign key 'FK__financial__item___46E78A0C' references invalid table 'transaction_id'.
How do I resolve this?
Yes, this is a correct script to create a foreign key
ALTER TABLE financial_transactions
ADD FOREIGN KEY (item_rental_id) REFERENCES customer_rentals(item_rental_id);
However, if you are trying to add a foreign key constraint on a table with data already in it, you have to make sure that the item_rental_id in financial_transactions table are also in the customer_rentals table. Otherwise, you will have a referential integrity error.
To illustrate:
CREATE TABLE customer_rentals_1
(item_rental_id INT,
PRIMARY KEY (item_rental_id)
);
CREATE TABLE financial_transactions_1
(transaction_id INT,
item_rental_id INT,
PRIMARY KEY (transaction_id)
);
ALTER TABLE financial_transactions_1
ADD FOREIGN KEY (item_rental_id) REFERENCES customer_rentals_1(item_rental_id);
The scripts above will run successfully.
CREATE TABLE customer_rentals_2
(item_rental_id INT,
PRIMARY KEY (item_rental_id)
);
CREATE TABLE financial_transactions_2
(transaction_id INT,
item_rental_id INT,
PRIMARY KEY (transaction_id)
);
INSERT INTO financial_transactions_2
VALUES (1000, 9999);
ALTER TABLE financial_transactions_2
ADD FOREIGN KEY (item_rental_id) REFERENCES customer_rentals_2(item_rental_id);
But, this will have the following error since item_rental_id 9999 is not present in customer_rentals_2 table
Msg 547, Level 16, State 0, Line 31
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__financial__item___76969D2E". The conflict occurred in database "TESTDB", table "dbo.customer_rentals_2", column 'item_rental_id'.
You have to give second table name
both way can do it
1. Add reference without name
ALTER TABLE financial_transactions
ADD FOREIGN KEY (item_rental_id) REFERENCES customer_rentals(item_rental_id);
2.Add reference with a name
ALTER TABLE financial_transactions
ADD CONSTRAINT FK_Financial_Transactions_Customer_Rental_Item_Rental_ID
FOREIGN KEY (item_rental_id) REFERENCES Customer_rentals(item_rental_id);

ALTER COLUMN Command doesn't work SQL Server

i want to add to a primary key in one table a references to the primary key of another table.
my code:
CREATE TABLE[payment]
(ID int Primary key)
CREATE TABLE [tab]
(ID int Primary key references tab2(ID))
Alter Table payment
alter column ID
ADD constraint fk_payment
references tab(ID)
i get the error that the syntax near constraint is wrong, but i don't know what to change
because of the not changeable order of the table Alter table is the only option. to reference from one table to the other doesn't work cause I've references from that table to another one already.
i need two one-to-one-relations from one table to another
If you want to add a FK constraint, just use this code:
ALTER TABLE dbo.payment
ADD CONSTRAINT fk_payment
FOREIGN KEY(ID) REFERENCES dbo.tab(ID)
You don't need to alter the column or table - just add the constraint

How to add a foreign key referring to itself in SQL Server 2008?

I have not seen any clear, concise examples of this anywhere online.
With an existing table, how do I add a foreign key which references this table? For example:
CREATE TABLE dbo.Projects(
ProjectsID INT IDENTITY(1,1) PRIMARY KEY,
Name varchar(50)
);
How would I write a command to add a foreign key which references the same table? Can I do this in a single SQL command?
I'll show you several equivalent ways of declaring such a foreign key constraint. (This answer is intentionally repetitive to help you recognise the simple patterns for declaring constraints.)
Example: This is what we would like to end up with:
Case 1: The column holding the foreign keys already exists, but the foreign key relationship has not been declared / is not enforced yet:
In that case, run this statement:
ALTER TABLE Employee
ADD FOREIGN KEY (ManagerId) REFERENCES Employee (Id);
Case 2: The table exists, but it does not yet have the foreign key column:
ALTER TABLE Employee
ADD ManagerId INT, -- add the column; everything else is the same as with case 1
FOREIGN KEY (ManagerId) REFERENCES Employee (Id);
or more succinctly:
ALTER TABLE Employee
ADD ManagerId INT REFERENCES Employee (Id);
Case 3: The table does not exist yet.
CREATE TABLE Employee -- create the table; everything else is the same as with case 1
(
Id INT NOT NULL PRIMARY KEY,
ManagerId INT
);
ALTER TABLE Employee
ADD FOREIGN KEY (ManagerId) REFERENCES Employee (Id);
or, declare the constraint inline, as part of the table creation:
CREATE TABLE Employee
(
Id INT NOT NULL PRIMARY KEY,
ManagerId INT,
FOREIGN KEY (ManagerId) REFERENCES Employee (Id)
);
or even more succinctly:
CREATE TABLE Employee
(
Id INT NOT NULL PRIMARY KEY,
ManagerId INT REFERENCES Employee (Id)
);
P.S. regarding constraint naming: Up until the previous revision of this answer, the more verbose SQL examples contained CONSTRAINT <ConstraintName> clauses for giving unique names to the foreign key constraints. After a comment by #ypercube I've decided to drop these clauses from the examples, for two reasons: Naming a constraint is an orthogonal issue to (i.e. independent from) putting the constraint in place. And having the naming out of the way allows us to focus on the the actual adding of the constraints.
In short, in order to name a constraint, precede any mention of e.g. PRIMARY KEY, REFERENCES, or FOREIGN KEY with CONSTRAINT <ConstraintName>. The way I name foreign key constraints is <TableName>_FK_<ColumnName>. I name primary key constraints in the same way, only with PK instead of FK. (Natural and other alternate keys would get the name prefix AK.)
You can add the column and constraint in one operation
ALTER TABLE dbo.Projects ADD
parentId INT NULL,
CONSTRAINT FK FOREIGN KEY(parentid) REFERENCES dbo.Projects
Optionally you could specify the PK column in brackets after the referenced table name but it is not needed here.
If the table already exists: Assuming you don't already have a column to store this data. If you do then skip this step.
ALTER TABLE [dbo].[project]
ADD [fkProjectsId] INT;
GO
ALTER TABLE [dbo].[projects]
ADD CONSTRAINT [FK_Projects_ProjectsId] FOREIGN KEY ([fkProjectsId]) REFERENCES [dbo].[Projects] ([ProjectsID])
GO

Differences between "foreign key" and "constraint foreign key"

I mean for example I can create table like
create table XTable
(
idt int not null primary key,
value nvarchar(50),
idq int,
constraint fk_idq foreign key(idq) references YTable(idq)
)
and I can create it like this
create table XTable
(
idt int not null primary key,
value nvarchar(50),
idq int,
foreign key(idq) references YTable(idq)
)
I usually create table like in the second example but now I'm curious about the first example. What is the difference?
The first one assigns a user-defined name to the foreign key, the second one will assign a system-generated name to the foreign key.
User-defined foreign key names can be useful for subsequent statements like these:
ALTER TABLE XTable DROP CONSTRAINT fk_idq;
ALTER TABLE XTable ENABLE CONSTRAINT fk_idq;
ALTER TABLE XTable DISABLE CONSTRAINT fk_idq;
It's harder to alter constraints with system-generated names, as you have to discover those names first.
The first option is purely for naming the constraint.
From SQL FOREIGN KEY Constraint
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)
Also, from CREATE TABLE (Transact-SQL) one can see that [ CONSTRAINT constraint_name ] is optional.
Apart from controlling the name, nothing really. SQL Server will supply a name if you omit it. FYI, you only need this syntax (SQL Fiddle):
create table XTable
(
idt int not null primary key,
value nvarchar(50),
idq int references YTable(idq)
)
Here's a fuller example.