Adding Primary keys and a Relationship to tables - sql

I have compiled the following as an example of what i have done so far and would like to know how i should continue:
CREATE TABLE tblMembers
(
Member_ID int,
Name varchar(255)
);
CREATE TABLE tblHorses
(
Horse_ID int,
Name varchar(255),
Age int(10),
Member_ID int(10)
);
So i would like to specify both Member_ID and Horse_ID as the PK and create the relationship between tblMembers and tblHorses using Member_ID
I would also like to make the ID columns auto incremental
Thank you in advance

Is this what you ware asking?
CREATE TABLE tblMembers (
Member_ID int identity(1, 1) not null primary key
Name varchar(255)
);
CREATE TABLE tblHorses (
Horse_ID int identity(1, 1) not nullprimary key
Name varchar(255),
Age int,
Member_ID int references tblMembers(member_id)
);
Storing something like "age" in a column is a really bad idea. After all, age continually changes. You should be storing something like the date of birth.

CREATE TABLE tblMembers
(
Member_ID int AUTO_INCREMENT,
Name varchar(255)
PRIMARY KEY (MEMBER_ID)
);
CREATE TABLE tblHorses
(
Horse_ID int,
Name varchar(255),
Age int(10),
FOREIGN KEY (MEMBER_ID) REFERENCES tblMembers(MEMBER_ID)
PRIMARY KEY (HORSE_ID)
);
Following W3Schools' examples.

Use this. Fiddler Demo
Refer this for creating Primary Key,Foreign Key, Identity .
CREATE TABLE tblMembers
(
Member_ID int IDENTITY(1,1) Primary Key,
Name varchar(255)
);
CREATE TABLE tblHorses
(
Horse_ID int IDENTITY(1,1) Primary Key,
Name varchar(255),
Age int,
Member_ID int Foreign key (Member_ID) REFERENCES tblMembers(Member_ID)
);
Note: MS SQL doesn't support length in Integer Type.

try this
CREATE TABLE [dbo].[tblMembers](
[Member_ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](255) NOT NULL,
CONSTRAINT [PK_tblMembers] PRIMARY KEY CLUSTERED
(
[Member_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[tblHorses](
[Horse_ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](255) NULL,
[Age] [int] NULL,
[Member_ID] [int] NOT NULL,
CONSTRAINT [PK_tblHorses] PRIMARY KEY CLUSTERED
(
[Horse_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[tblHorses] WITH CHECK ADD CONSTRAINT [FK_tblHorses_tblMembers] FOREIGN KEY([Member_ID])
REFERENCES [dbo].[tblMembers] ([Member_ID])
GO
ALTER TABLE [dbo].[tblHorses] CHECK CONSTRAINT [FK_tblHorses_tblMembers]
GO

For Auto Incremental, you have to set PK column as identity(seed, value)
CREATE TABLE tblMembers (
Member_ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY
Name VARCHAR(255)
);
CREATE TABLE tblHorses (
Horse_ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY
Name VARCHAR(255),
Age INT,
Member_ID int REFERENCES tblMembers(Member_id)
);

Try below
CREATE TABLE tblMembers (
Member_ID int identity(1, 1) not null
Name varchar(255)
PRIMARY KEY (Member_ID )
);
CREATE TABLE tblHorses (
Horse_ID int identity(1, 1) not null
Name varchar(255),
Age int,
PRIMARY KEY (Horse_ID)
Member_ID int references tblMembers(member_id)
);

Related

No Primary or candidate keys in the referenced table that match column list in foreign key

I am trying to create a few basic SQL tables however I keep getting the following error:
There are no primary or candidate keys in the referenced table 'CART' that match the referencing column list in the foreign key 'FK__ORDERS__CART_ID__2B3F6F97'
This is the current code which I am using.
create table USERS
(
User_ID int NOT NULL primary key,
Address varchar(30) NOT NULL,
Email varchar(30) NOT NULL,
Password varchar(30) NOT NULL,
Phone varchar(30) NOT NULL,
F_Name varchar(30) NOT NULL,
L_Name varchar(30) NOT NULL,
Date_of_Birth varchar(30) NOT NULL
)
create table PAYMENT
(
User_ID int NOT NULL primary key,
Credit_Card varchar(30) NOT NULL,
Debit_Card varchar(30) NOT NULL,
Google_Pay varchar(30) NOT NULL,
Apple_Pay varchar(30) NOT NULL,
Paypal varchar(30) NOT NULL,
foreign key (User_ID)
references USERS(User_ID)
)
create table CART
(
User_ID int NOT NULL,
Cart_ID int NOT NULL,
Total_Price float NOT NULL,
primary key (Cart_ID, User_ID),
foreign key(User_ID)
references USERS(User_ID)
)
create table ORDERS
(
Order_ID int NOT NULL primary key,
Total_Price float NOT NULL,
Payment_Method varchar(30) NOT NULL,
User_ID int NOT NULL,
CART_ID int NOT NULL,
foreign key (User_ID)
references USERS(User_ID),
foreign key (Cart_ID)
references CART(Cart_ID),
)
create table ORDER_HISTORY
(
User_ID int NOT NULL,
Order_ID int NOT NULL,
primary key (User_ID, Order_ID),
foreign key (User_ID)
references USERS(User_ID),
foreign key (Order_ID)
references ORDERS(Order_ID)
)
I have tried modifying things and moving them around but cannot get the error to go away. I suspect that this is probably quite simple and obvious but since I am so new to SQL I am probably missing it.
cart has a composite primary key (cart_id, order_id). Each of these columns aren't primary keys independently, just their combination. The foreign key from orders should act the same - you should have a single foreign key based on the combination of the two:
create table ORDERS
(
Order_ID int NOT NULL primary key,
Total_Price float NOT NULL,
Payment_Method varchar(30) NOT NULL,
User_ID int NOT NULL,
CART_ID int NOT NULL,
foreign key (User_ID)
references USERS(User_ID),
foreign key (Cart_ID, User_id) -- here
references CART(Cart_ID, User_id),
)
As table CART has composite primary key, then you should to reference to a composite primary key:
create table ORDERS
(
Order_ID int NOT NULL primary key,
Total_Price float NOT NULL,
Payment_Method varchar(30) NOT NULL,
User_ID int NOT NULL,
CART_ID int NOT NULL,
foreign key (User_ID)
references USERS(User_ID),
foreign key (Cart_ID, User_ID)
references CART(Cart_ID, User_ID),
)
In table Cart, you need to define Cart_ID with PRIMARY KEY. If for some reason you cannot or don't want to define a PRIMARY KEY then try UNIQUE KEY constraint on the same column.
It is the Primary Key on the Cart table.
CREATE TABLE [dbo].[CART](
[User_ID] [int] NOT NULL,
[Cart_ID] [int] NOT NULL,
[Total_Price] [float] NOT NULL,
CONSTRAINT [PK__CART__D6AB58B9B18E85A5] PRIMARY KEY CLUSTERED
(
[User_ID] ASC,
[Cart_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[CART] WITH CHECK ADD FOREIGN KEY([User_ID])
REFERENCES [dbo].[USERS] ([User_ID])

Error with foreign key SQL Server 2012

I have problem with adding foreign key in SQL Server 2012
create table Predracun
(
PredracunID int not null identity(1,1),
Iznos nvarchar(255),
Datum date,
Opis nvarchar(255)
)
create table Racun
(
RacunID int not null identity (1,1),
Sifra nvarchar(255),
BrojRacuna nvarchar(255)
)
create table Prijem
(
PrijemID int not null identity (1,1),
Datum date,
Opis nvarchar(255)
)
alter table Prijem
add constraint FK_PrijemPredracun
foreign key (PredracunID)
references Predracun (PredracunID)
added on this way
and I got error msg
Msg 1769, Level 16, State 1, Line 1
Foreign key 'FK_UredjajPrijem' references invalid column 'PrijemID' in referencing table 'Uredjaj'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
The column PredracunID does not exist in table prijem. Therefore it can't be used as a foreign key.
Use below scripts:
CREATE TABLE Predracun
(
PredracunID int not null identity(1,1),
Iznos nvarchar(255),
Datum date,
Opis nvarchar(255)
PRIMARY KEY CLUSTERED
(
[PredracunID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
create table Racun
(
RacunID int not null identity (1,1),
Sifra nvarchar(255),
BrojRacuna nvarchar(255)
)
create table Prijem
(
PrijemID int not null identity (1,1),
PredracunID int,
Datum date,
Opis nvarchar(255)
)
alter table Prijem
add constraint FK_PrijemPredracun
foreign key (PredracunID)
references Predracun (PredracunID)
Note: Foreign key can be created only on either primary key column or unique key column from reference table. You were missing two things in your script.
Predracun table is not having any key (Unique or Primary) column
To create foreign key in Prijem table you have to have PredracunID column in create table statement.

Unable to set foreign key for my computed column

I can't set the foreign key for my advertisement table or should I say how do I add datatype for my computed column in employer table ? error details below
CREATE Table Employer
(
No Int NOT NULL IDENTITY(1,1),
EmployerID AS 'EID'+ CAST(No as VARCHAR(50)) PERSISTED NOT NULL ,
CONSTRAINT PK_Employer PRIMARY KEY CLUSTERED(EmployerID),
EUsername CHAR(20) NOT NULL,
EPassword CHAR(20) NOT NULL,
Name VARCHAR(20) NOT NULL,
Contact_Number INT NOT NULL,
Email CHAR(20) NOT NULL,
Company_Name CHAR(30) NOT NULL,
Current_Position VARCHAR(30) NULL
);
CREATE Table Advertisement
(
No Int NOT NULL IDENTITY(1,1),
AdvertisementID AS 'AID'+ CAST(No as VARCHAR(10)) PERSISTED ,
CONSTRAINT PK_Advertisement PRIMARY KEY CLUSTERED(AdvertisementID) ,
Employer_ID VARCHAR(10) Foreign Key References Employer(EmployerID) NOT NULL,
Company_Name VARCHAR(30) NOT NULL,
Company_Location CHAR(30) NULL,
Job_Position VARCHAR(30)NOT NULL,
Job_Description VARCHAR(100) NULL,
Skills_Requirement VARCHAR(100) NULL,
Education_Requirement CHAR(50) NOT NULL,
Salary CHAR(20) NOT NULL
);
This is the error I keep getting :
Msg 1753, Level 16, State 0, Line 27
Column 'Employer.EmployerID' is not the same length or scale as referencing column 'Advertisement.EmployerID' in foreign key 'FK__Advertise__Emplo__07C12930'. Columns participating in a foreign key relationship must be defined with the same length and scale.
Msg 1750, Level 16, State 0, Line 27
Could not create constraint or index. See previous errors.
note that the foreign key relationship must be defined with the same length and scale for both foreign key and primary key
so you must set EmployerID field to varchar(50) in advertisement table
Its recommended to use BIGINT auto increment field type for EmployerID.
and use Employer table's EmployerID field as you foreign key.
CREATE TABLE [Employer](
[EmployerID] [bigint] IDENTITY(1,1) NOT NULL,
[EUsername] [char](20) NOT NULL,
[EPassword] [char](20) NOT NULL,
[Name] [varchar](20) NOT NULL,
[Contact_Number] [int] NOT NULL,
[Email] [char](20) NOT NULL,
[Company_Name] [char](30) NOT NULL,
[Current_Position] [varchar](30) NULL,
CONSTRAINT [PK_Employer] PRIMARY KEY CLUSTERED
(
[EmployerID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [Advertisement](
[AdvertisementID] [bigint] IDENTITY(1,1) NOT NULL,
[fk_Employer_ID] [bigint] NOT NULL,
[Company_Name] [varchar](30) NOT NULL,
[Company_Location] [char](30) NULL,
[Job_Position] [varchar](30) NOT NULL,
[Job_Description] [varchar](100) NULL,
[Skills_Requirement] [varchar](100) NULL,
[Education_Requirement] [char](50) NOT NULL,
[Salary] [char](20) NOT NULL,
CONSTRAINT [PK_Advertisement] PRIMARY KEY CLUSTERED
(
[AdvertisementID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
ALTER TABLE [Advertisement] WITH CHECK ADD CONSTRAINT [FK_Advertisement_Employer] FOREIGN KEY([fk_Employer_ID])
REFERENCES [Employer] ([EmployerID])
ALTER TABLE [Advertisement] CHECK CONSTRAINT [FK_Advertisement_Employer]

Creating a table with a compound primary key

Ok I want to create a table
TABLE log_table
email nvarchar(255)
,salesrep nvarchar(20)
,blastid int
,timestamp datetime
Now the default value for the timestamp would be the datetime of when the record is inserted and I want the primary key to be on email and blastid.
I know you can do it with clustered indexes but I am not sure on the syntax on how to make that happen. Please, any help would be greatly appreciated. I am using SQL Server Management Studio 2008
CREATE TABLE dbo.log_table
(
email nvarchar(255) NOT NULL,
salesrep nvarchar(2) NULL,
blastid int NOT NULL,
timestamp datetime NULL
)
ALTER TABLE dbo.log_table ADD CONSTRAINT
DF_log_table_timestamp DEFAULT GetDate() FOR timestamp
ALTER TABLE dbo.log_table ADD CONSTRAINT
PK_log_table PRIMARY KEY CLUSTERED
(
email,
blastid
)
GO
If you are using the create table GUI, you can use control while clicking columns to set as primary keys.
CONSTRAINT PK_LOG_TBL PRIMARY KEY CLUSTERED (email ASC, email ASC)
CREATE TABLE log_table (
email NVARCHAR(255) NOT NULL,
salesrep NVARCHAR(255),
blastid INT,
[timestamp] DATETIME,
PRIMARY KEY (email, blastid)
)
I believe the timestamp default would be accomplished with 'GETDATE()' on insert.
You need to create a composite primary key. the syntax is as follows:
CREATE TABLE log_table
(
email nvarchar(255),
salesrep nvarchar(20),
blastid int,
timestamp datetime,
PRIMARY KEY (email, blastid)
)
I would use something else rather than "timestamp" - that is a sql server data type.
create table log_table
(
email nvarchar(255) not null
,salesrep nvarchar(20)
,blastid int not null
,timestamp datetime default getdate())
ALTER TABLE dbo.log_table ADD CONSTRAINT
PK_log_table PRIMARY KEY CLUSTERED
(
email, blastid
) WITH( STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

Database design - How can I have a foreign key of the primary key in the same table?

My database has to store all the available departments in my company.
Some departments are sub-departments on another existing department. I've decided to solve this like this:
Departments
ID Description HeadOfDepartment ParentDepartment
ParentDepartment can be null, indicating it is a root department. If it has a parent I'll act accordingly, my question is how can I code this in Microsoft SQL?
CREATE TABLE Departments
(
ID integer primary key,
Description varchar(255),
HeadOfDepartment varchar(255),
ParentDepartment integer references Departments(ID)
);
Foreign keys in SQL Server are allowed to be either NULL OR a valid key in the appropriate table.
CREATE TABLE [hierarchytest](
[ID] [int] NOT NULL,
[ParentID] [int] NULL,
CONSTRAINT [PK_hierarchytest] PRIMARY KEY CLUSTERED
(
[ID] ASC
))
GO
ALTER TABLE [hierarchytest] WITH CHECK ADD CONSTRAINT [FK_hierarchytest_hierarchytest] FOREIGN KEY([ParentID])
REFERENCES [hierarchytest] ([ID])
GO
ALTER TABLE [hierarchytest] CHECK CONSTRAINT [FK_hierarchytest_hierarchytest]
If you create a foreign key, and enforce it, then you'll not be allowed to put null values in the foreign key field. If I were to implement something like this, I would enforce the foreign key constraint, and simply fill the foreign key value of a department with no parent with it's own primary key. That should be allowed.
CREATE TABLE Departments
(
Id INT PRIMARY KEY,
Description VARCHAR(255),
HeadOfDepartment VARCHAR(255),
ParentDepartment INT NOT NULL REFERENCES Departments(Id)
);
Create a foreign key on ParentDepartment that refrences the ID property of the table.
CREATE TABLE dbo.Departments
(
ID int NOT NULL IDENTITY (1, 1),
Description nvarchar(100) NOT NULL,
HeadOfDepartment nvarchar(100) NOT NULL,
ParentDepartment int NULL
) ON [PRIMARY]
ALTER TABLE dbo.Departments ADD CONSTRAINT
PK_Departments PRIMARY KEY CLUSTERED
(
ID
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
ALTER TABLE dbo.Departments ADD CONSTRAINT
FK_Departments_Departments FOREIGN KEY
(
ParentDepartment
) REFERENCES dbo.Departments
(
ID
) ON UPDATE NO ACTION
ON DELETE NO ACTION