Adding Foreign key relationships in SQL server using T-SQL fails - sql-server

I've been trying to create a table(name - "UserItem") with foreign keys from two previously created tables(names - "EndUser" , "Item") but i keep getting the error
Msg 102, Level 15, State 1, Line 9
Incorrect syntax near 'GO'.
The code syntax for creating the Table is
CREATE TABLE UserItem (
userID int NOT NULL,
itemName varchar(25) NOT NULL,
CONSTRAINT FK_uid FOREIGN KEY (userID) REFERENCES EndUser (userID),
CONSTRAINT FK_iname FOREIGN KEY (itemName) REFERENCES Item (itemName)
ON DELETE CASCADE
ON UPDATE CASCADE
)GO
The syntax for the two previously created Tables are as follows,
CREATE TABLE EndUser(
userID int PRIMARY KEY NOT NULL,
userName varchar(25) NOT NULL,
userPW varchar(8) NOT NULL
)GO
CREATE TABLE Item(
itemName varchar(25) PRIMARY KEY NOT NULL,
tag1 varchar(20) NOT NULL,
tag2 varchar(20) NOT NULL,
tag3 varchar(20) NOT NULL,
)GO
Im using Visual studio 2015 if that helps in any way.

Just by removing GO it will work

Related

Can I auto-increment the Foreign Key column in my db table so that it matches the main table's auto-incrementing Primary Key column in SQL Server?

Create statement for my first table: 'users':
CREATE TABLE users
(
uid INT NOT NULL IDENTITY PRIMARY KEY,
firstName VARCHAR(50) NOT NULL,
lastName VARCHAR(50) NOT NULL,
middle VARCHAR(50) NOT NULL,
ssn VARCHAR(12) NOT NULL,
dob DATE NOT NULL,
phone VARCHAR(10) NOT NULL,
email VARCHAR(255) NOT NULL
)
Create statement for my second table: 'ds':
CREATE TABLE ds
(
dsu VARCHAR(50) NOT NULL,
dsp VARCHAR(50) NOT NULL,
dsImage VARCHAR(50) NOT NULL,
dsid INT NOT NULL,
Name nvarchar(50),
CONSTRAINT PK_dsid
PRIMARY KEY NONCLUSTERED (dsid),
CONSTRAINT FK_users_uid
FOREIGN KEY (dsid) REFERENCES users (uid)
ON DELETE CASCADE
ON UPDATE CASCADE
);
The first table's uid column will auto-increment with each new row I insert. I want to setup the ds table's dsid column value in each new row to automatically update to match the users table uid column value.
When I try to INSERT INTO values into the ds table:
INSERT INTO ds (dsu, dsp, dsImage)
VALUES ('john.smith', '1234567', 'Tiger')
I get the following error:
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'dsid', table 'company.dbo.ds'; column does not allow nulls. INSERT fails.
So, I'm trying to figure out if I'm setting up the primary key and foreign key create statements correctly to achieve the desired result, and also why I'm getting the error, and if I'm even approaching this task/problem correctly.
Any help is greatly appreciated, thank you!

SQL Server : foreign key references invalid table

I'm not sure what I'm doing wrong, but I'm getting a foreign key references invalid table message telling me that dbo.ValueStream is an invalid table.
Edit: I originally posted my code in the incorrect order. Fixed in the edit to reflect the order it was done in SSMS
CREATE TABLE dbo.ValueStream
(
ValueStreamKey int IDENTITY(1,1) NOT NULL
CONSTRAINT PK_ValueStream_ValueStreamKey PRIMARY KEY,
ValueStream nvarchar(20),
)
CREATE TABLE dbo.NonConformance
(
NonConformanceKey int IDENTITY(1,1) NOT NULL
CONSTRAINT PK_NonConformance_NonConformanceKey PRIMARY KEY,
CustomerVendorKey int NOT NULL
CONSTRAINT FK_NonConformance_CustomerVendorKey_CustomerVendor_CustomerVendorKey
FOREIGN KEY REFERENCES dbo.CustomerVendor(CustomerVendorKey),
ValueStreamKey int NOT NULL
CONSTRAINT FK_NonConformance_ValueStream_Key_ValueStream_ValueStreamKey
FOREIGN KEY REFERENCES dbo.ValueStream(ValueStreamKey),
RepairOrder nvarchar(50) NOT NULL,
WorkOrder nvarchar(8) NOT NULL,
PartNumber nvarchar(50) NOT NULL,
SerialNumber nvarchar(50) NOT NULL,
PartDescription nvarchar(50) NOT NULL,
InductionDate datetime NOT NULL,
TriageStartDate datetime NOT NULL,
TriageCompletionDate datetime NOT NULL,
RequiresRRCA Bit NOT NULL,
NonConformanceSummary nvarchar(max) NOT NULL
);
taking out the CONSTRAINT FK_NonConformance_CustomerVendorKey_CustomerVendor_CustomerVendorKey
FOREIGN KEY REFERENCES dbo.CustomerVendor(CustomerVendorKey)
(we don't have that one)
and running the scripts seperately - first the first table and then the creation of the referencing table - this works for me.
No code errors.
You are creating dbo.NonConformance first in the script that you have posted. You need to move the CREATE TABLE dbo.ValueStream statement so that it is created first, ensuring there is a GO statement still between the two CREATE TABLE statements.
As it stands you are trying to create a foreign key to a table that does not exist.

SQL create table using code and populate with code

I'm working on an assignment and have created my code on NotePad++ to then copy over to SSMS, however when I create a table it brings me to the default view which is manually entering the column names and data. I want to just paste my created code into the database to create the table. How do I go about this?
Also my prof has provided data to populate my tables but I can't seem to figure out where I paste his INSERT INTO data into?
Also, for some reason I attempted to create a new query in the database i created for the assignment and pasted the code into that, but the tables don't show up even if I execute them in the Tables drop down.
Code for notepad++
CREATE TABLE tblMajors
(
MajorCode varchar(10) PRIMARY KEY NOT NULL,
MajorDescription varchar(MAX) NOT NULL,
)
CREATE TABLE tblInstructors
(
InstructorNumber int PRIMARY KEY NOT NULL,
InstructorFirst varchar(50) NOT NULL,
InstructorLast varchar(50) NOT NULL,
ContractStatus varchar(10) NOT NULL,
PhoneNumber bigint NOT NULL,
)
CREATE TABLE tblStudents
(
StudentNumber int PRIMARY KEY NOT NULL,
StudentFirst varchar(20) NOT NULL,
StudentLast varchar(20) NOT NULL,
MajorCode varchar(10) FOREIGN KEY REFERENCES tblMajors (MajorCode),
)
CREATE TABLE tblCourses
(
CourseCode varchar(10) PRIMARY KEY NOT NULL,
CourseDescription varchar(MAX) NOT NULL,
)
CREATE TABLE tblGrades
(
StudentNumber bigint FOREIGN KEY REFERENCES tblStudents (StudentNumber),
CourseCode varchar(10) FOREIGN KEY REFERENCES tblCourses (CourseCode),
Grade int NOT NULL,
IntructorNumber int FOREIGN KEY REFERENCES tblInstructors (IntructorNumber),
PRIMARY KEY (StudentNumber, CourseCode)
)

Foreign Key Constraint does not exist ERROR

I keep getting this error in my psql database;
bikefacility=# ERROR: syntax error at or near "c"
bikefacility-# LINE 1: c
bikefacility-# ^
bikefacility-# bikefacility=# ALTER TABLE bicycle ADD CONSTRAINT fk_maintenance_contact_person FOREIGN KEY (maintenance_contact_person) REFERENCES maintenance(maintenance_contact_person);
ERROR: syntax error at or near "ERROR"
LINE 1: ERROR: syntax error at or near "c"
^
bikefacility=# ERROR: column "maintenance_contact_person" referenced in foreign key constraint does not exist
bikefacility-# bikefacility=# ALTER TABLE bicycle ADD CONSTRAINT fk_rental_period FOREIGN KEY (rental_period) REFERENCES rental(rental_period);
ERROR: syntax error at or near "ERROR"
LINE 1: ERROR: column "maintenance_contact_person" referenced in fo...
^
bikefacility=# ERROR: column "rental_period" referenced in foreign key constraint does not exist
bikefacility-# bikefacility=# ALTER TABLE bicycle ADD CONSTRAINT fk_terminal_id FOREIGN KEY (terminal_id) REFERENCES terminal(terminal_id);
ERROR: syntax error at or near "ERROR"
LINE 1: ERROR: column "rental_period" referenced in foreign key con...
^
bikefacility=# ERROR: column "terminal_id" referenced in foreign key constraint does not exist
This is my code. I've created the same style of foreign keys within the code as you can see here.
CREATE TABLE member (
member_id INTEGER PRIMARY KEY,
member_fname VARCHAR(15) NOT NULL,
member_lname VARCHAR(15) NOT NULL,
member_status VARCHAR(15) NOT NULL,
member_address VARCHAR(10) NOT NULL,
member_email VARCHAR(30) NOT NULL
);
CREATE TABLE bicycle (
bicycle_id INTEGER PRIMARY KEY,
bicycle_brand VARCHAR(25) NOT NULL,
bicycle_model VARCHAR(25) NOT NULL,
bicycle_colour VARCHAR(15) NOT NULL,
bicycle_type VARCHAR(20) NOT NULL,
bicycle_size VARCHAR(10) NOT NULL,
bicycle_availability VARCHAR(20) NOT NULL
);
ALTER TABLE bicycle ADD CONSTRAINT fk_bicycle_pickup_date FOREIGN KEY (bicycle_pickup_date) REFERENCES rental(bicycle_pickup_date) >MATCH FULL;
ALTER TABLE bicycle ADD CONSTRAINT fk_maintenance_contact_person FOREIGN KEY (maintenance_contact_person) REFERENCES maintenance(maintenance_contact_person);
ALTER TABLE bicycle ADD CONSTRAINT fk_terminal_id FOREIGN KEY (terminal_id) REFERENCES terminal(terminal_id);
ALTER TABLE bicycle ADD CONSTRAINT fk_rental_period FOREIGN KEY (rental_period) REFERENCES rental(rental_period);
CREATE TABLE sponsor (
sponsor_id INTEGER PRIMARY KEY,
sponsor_name VARCHAR(15) NOT NULL,
sponsor_contact VARCHAR(30) NOT NULL,
sponsor_period DATE NOT NULL,
sponsor_address VARCHAR(50) NOT NULL,
sponsor_fee DECIMAL (6, 2) NOT NULL
);
CREATE TABLE terminal (
terminal_id INTEGER PRIMARY KEY,
terminal_address VARCHAR(50) NOT NULL,
terminal_minstorage VARCHAR(50) NOT NULL,
terminal_maxstorage VARCHAR(50) NOT NULL
);
CREATE TABLE rental (
rental_no INTEGER PRIMARY KEY,
rental_period DATE NOT NULL,
bicycle_pickup_date DATE NOT NULL
);
It says that the columns don't exist but I know they do because they're right there! Can someone help me out, please? Thanks in advance!
The grammar of the the foreign keys are incorrect for postgresql. For instance, ALTER TABLE bicycle ADD CONSTRAINT fk_terminal_id FOREIGN KEY (terminal_id) REFERENCES terminal(terminal_id); requires there to be a field in bicycles, named terminal_id as the former terminal_id in your query refers to bicycle table, which should reference terminal_id in the terminal table.
Here is a short tutorial of foreign keys. https://www.postgresqltutorial.com/postgresql-foreign-key/
Best regards,
Bjarni
Your schema is quite messed up.
There's no table maintenance yet you try to make a reference to it.
The foreign table like rental must be created before you make a fk reference to it.
You must have the named fields in the table where you make the reference from. There are no fields bicycle_pickup_date, maintenance_contact_person, terminal_id or rental_period in table bicycle.
Your fk references in general sound odd. Do you really want that each bicycle could have only only one rental, ever? Maybe you meant that a rental references to a single bicycle?
Also, your naming convention is quite redundant. There's no need to repeat table name in each field name, that just adds unneeded clutter in your code.

SQL Relation MORE on MORE

I have a question about this relation betweed SpelerTeam and Toernooi, i get a error, can someone help me with it all the other relations do work:
Msg 1776, Level 16, State 0, Line 2 There are no primary or candidate
keys in the referenced table 'SpelerTeam' that match the referencing
column list in the foreign key 'FK__Toernooi__team__1A14E395'. Msg
1750, Level 16, State 0, Line 2 Could not create constraint. See
previous errors.
CREATE TABLE dbo.LoginGegevens
(
Username varchar(25) NOT NULL,
Wachtwoord varchar(25) NOT NULL,
LoginDatum date NOT NULL,
)
CREATE TABLE dbo.NawGegevensKind
(
KindSpeler varchar(25) NOT NULL,
NawKind varchar(50) NOT NULL,
)
CREATE TABLE dbo.NawGegevensProfspeler
(
Profspeler varchar(25) NOT NULL,
NawProfspeler varchar(50) NOT NULL,
)
CREATE TABLE dbo.SpelerTeam
(
Team int NOT NULL,
Kindspeler varchar(25) NOT NULL,
Profspeler varchar(25) NOT NULL,
)
CREATE TABLE dbo.Toernooi
(
team int NOT NULL,
score int NOT NULL,
games int NOT NULL,
rondes int NOT NULL,
)
-- primary keys
ALTER TABLE LoginGegevens
ADD primary KEY (Username)
ALTER TABLE NawGegevensKind
ADD primary KEY (KindSpeler)
ALTER TABLE NawGegevensProfspeler
ADD primary KEY (ProfSpeler)
ALTER TABLE SpelerTeam
ADD primary KEY (Team,KindSpeler,ProfSpeler)
ALTER TABLE Toernooi
ADD primary KEY (Team,Rondes,Games)
-- relation
ALTER TABLE SpelerTeam
ADD FOREIGN KEY (Kindspeler)
REFERENCES NawGegevensKind(Kindspeler);
ALTER TABLE SpelerTeam
ADD FOREIGN KEY (Profspeler)
REFERENCES NawGegevensProfspeler(Profspeler);
ALTER TABLE Toernooi
ADD FOREIGN KEY (Team)
REFERENCES SpelerTeam(Team);
The Primary Key of SpelerTeam is Team,KindSpeler,ProfSpeler.
That means that any foreign key that references that table has to reference all three of those columns. You can't create a foreign key that uses only team.
You need an index on a colum so that it can be referenced as a foreign key efficiently. Add an index on SpelerTeam.Team and on all other columns with the same problem. Try CREATE INDEX IX_SpelerTeam_Team_Team ON SpelerTeam (Team);
Add below after all tables have been created:
CREATE UNIQUE NONCLUSTERED INDEX IX_SpelerTeam_Team
ON dbo.SpelerTeam (Team);
GO
As it was pointed in another answer you cannot reference to non unique column, to make column unique you can make this column primary key or create index for this column.
It is not enough that your "Team" column is part of composite key.

Resources