foreign keys in sql server 2005 - sql-server

I having trouble creating a foreign key in sql 2005.
my primary key table has a primary key that spans 2 columns.
I want to create my foreign key so it references a column in my primary table but I want to specify a static value for the second column - is this possible?

No, you cannot do this - if you reference a parent table from a child table, you have to reference all columns of the primary key on the parent table:
ALTER TABLE dbo.ChildTable
ADD CONSTRAINT FK_ChildTable_ParentTable
FOREIGN KEY (col1, col2) REFERENCES dbo.ParentTable(pkCol1, pkCol2)
You cannot suddenly introduce for "static" value into your reference.
What you could do on the child table would be to put a CHECK CONSTRAINT on that second column to make it a "static" value - but then you can never have any other value in that column:
ALTER TABLE dbo.ChildTable
ADD CONSTRAINT chk_col2_Static CHECK (col2 = 4)
Is that what you are looking for??

Related

Add primary key to the table coulmn(please see the attached image for more clarity)

Creating table without using SQL table feature:
I'm trying to create table going to "Tables","Create Table" feature. How do I add primary and unique keys using this feature.
Right click on the selected column and set the option primary key from the context menu.
It has been shown below.
The documentation covers this nicely: From Create Primary Keys
Using SQL Server Management Studio
To create a primary key
In Object Explorer, right-click the table to which you want to add a unique constraint, and click Design.
In Table Designer, click the row selector for the database column you want to define as the primary key. If you want to select multiple
columns, hold down the CTRL key while you click the row selectors for
the other columns.
Right-click the row selector for the column and select Set Primary Key.
Or, if you want to use Transact-sQL
Using Transact-SQL
To create a primary key in an existing table
The following example creates a primary key on the column
TransactionID in the AdventureWorks database.
ALTER TABLE Production.TransactionHistoryArchive
ADD CONSTRAINT PK_TransactionHistoryArchive_TransactionID PRIMARY KEY CLUSTERED (TransactionID);
It also goes on to explain how you can use T-SQL to create a NONCLUSTERED Primary key, and then add a further CLUSTERED INDEX on the table:
To create a primary key with clustered index in a new table
The following example creates a table and defines a primary key on the
column CustomerID and a clustered index on TransactionID in the
AdventureWorks database.
-- Create table to add the clustered index
CREATE TABLE Production.TransactionHistoryArchive1
(
CustomerID uniqueidentifier DEFAULT NEWSEQUENTIALID()
, TransactionID int IDENTITY (1,1) NOT NULL
, CONSTRAINT PK_TransactionHistoryArchive1_CustomerID PRIMARY KEY NONCLUSTERED (CustomerID)
)
;
-- Now add the clustered index
CREATE CLUSTERED INDEX CIX_TransactionID ON Production.TransactionHistoryArchive1 (TransactionID);

How to add another primary key in SQL Server

I have a SQL Server table that has primary keys
CompanyID
ClientID
ReportName
I need to add a column that is an additional key and an incremented ID.
alter table Exports
add id int identity(1,1)
How do I write the statement to make this a key as well?
You can have only 1 primary key or identity column in each table in SQL Server.
If you want to have one more column as primary key, then you may use the combination of the columns as the primary key.
Or you can set the constraints UNIQUE and NOT NULL to the columns so that they will act same as a primary key (but these columns can't be referred as foreign keys)
In case of auto incremental columns (identity), you can only have 1 identity column per table. It can also be set as a primary key. Otherwise, if you need multiple columns as auto-increment, then probably you can use a calculated column, a trigger or a sequence object from which you may fetch the values for each record

T-SQL inserting data into table with foreign key

I'm using SQL Server 2014 to create and insert data into tables and came along a problem when it comes to populating a table with a foreign key constraint in it. I have a table user and and a table city which were created beforehand.
I used code to alter the user table to include a cityId foreign key from table city with this code:
ALTER TABLE [Schema].[user]
ADD cityId UNIQUEIDENTIFIER NOT NULL
CONSTRAINT usr_cid_fk
FOREIGN KEY (cityId) REFERENCES [Schema].[city] (cityId);
GO
Basically I modified the user table by adding a field called cityId which i made foreign key. now the problem is that when inserting data, in the first line
INSERT INTO [Schema].[user](name, surname, dob, gender, .. )
cityId cannot be found to be mapped. Dunno why it ain't showing. In the design view it is listed as a foreign key so there should be no problems.
Thanks a lot
try :
ALTER TABLE [Schema].[user]
ADD cityId NUMBER NOT NULL
CONSTRAINT usr_cid_fk
FOREIGN KEY (cityId) REFERENCES [Schema].[city] (cityId);
Note :
For ADD cityId UNIQUEIDENTIFIER NOT NULL
By the SQL standard, a foreign key must reference either the primary key or a unique key of the parent table. If the primary key has multiple columns, the foreign key must have the same number and order of columns. Therefore the foreign key references a unique row in the parent table; there can be no duplicates.

Foreign key linked with primary key in same table

I have a table Categories with columns Id, ParentId (for "subcategories" whom can have any level of nesting) and some other. Using SQL Server 2012 I can't make foreign key in same table, FK_Categories_Categories (Id -> ParentId).
Error message is
'Categories' table
- Unable to create relationship 'FK_Categories_Categories'. The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Categories_Categories". The conflict occurred in database "pokupaykadb", table "dbo.Categories", column 'Id'.
That needs for cascade deletion of subcategories. What solution can be? It's desirable to be a some property, like cascade deletion from another table by foreign key
http://i.stack.imgur.com/kXiMS.png
If there are orphaned records that does not meet your constraint criteria - delete them before creating the foreign key.
Usually there are few records which doesn't go by the new constraint and that the DBMS doesn't allow to create the constraint.
In the case of orphaned values, the first occurrence is provided in the error label with the value that is orphaned.
It would certainly have helped to see what code you have tried to execute.
Below is a valid table definition :
CREATE TABLE dbo.Categories
(
Id int NOT NULL IDENTITY(-2147483648, 1)
CONSTRAINT PK_Categories PRIMARY KEY
, ParentId int NOT NULL
CONSTRAINT FK_Categories_ParentId
FOREIGN KEY (ParentId) REFERENCES dbo.Categories
)

How to use foreign key of sqlite to link three table 1->2->3 different column

I am having three table i want to link all three table together.
for example :
table1 : create table master (sr_no int,int,name text);
table2 : create table child1 (sr_no int,emplno int,last_name text,foreign key(sr_no) refernces master(sr_no) on delete cascade on update cascade);
table3 : create table child2 (Em int,phone text,foreign key(Em) refernces child1(emplno) on delete cascade on update cascade);
But when inserting data into table3 its show ===> Error: foreign key mismatch
please tell me whts problem
thank you
http://www.sqlite.org/foreignkeys.html#fk_indexes
Foreign key DML errors are may be reported if:
The parent table does not exist, or
The parent key columns named in the foreign key constraint do not exist, or
The parent key columns named in the foreign key constraint are not the primary key of the parent table and are not subject to a unique constraint using collating sequence specified in the CREATE TABLE, or
The child table references the primary key of the parent without specifying the primary key columns and the number of primary key columns in the parent do not match the number of child key columns.
Is emplno the primary key in child2?
The documentation says:
the parent key columns must be collectively subject to a UNIQUE constraint or have a UNIQUE index
Add a UNIQUE constraint to child1'S emplno field, or create a separate index on it.

Resources