SQL Server : foreign key references invalid table - sql-server

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.

Related

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)
)

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

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

SQL Server & Visual Studio - Insert Data in tables doesn't work

I want to insert my tables from my SQL Server Management Studio code with data via Visual Studio.
But it doesn't work. The ID of my table doesn't get a value automatically (but I have command it with identity(1,1)) and an error appears that it stands in conflict with a foreign-key-constraint.
create table [ProduktZahlungFENutzer]
(
ID int PRIMARY KEY IDENTITY(1,1) NOT NULL,
Endpreis decimal(3, 2)
);
CREATE TABLE [FHAngehörige]
(
FHAngehörigeID INT NOT NULL IDENTITY(1,1)
PRIMARY KEY Constraint fhA_feN
REFERENCES FENutzer(FENutzerID),
Name VARCHAR(50) NOT NULL,
Fachbereich INT NOT NULL,
Email VARCHAR(50) NOT NULL UNIQUE
)
CREATE TABLE [FENutzer]
(
FENutzerID INT IDENTITY(1,1) NOT NULL
PRIMARY KEY constraint t_nutzer
references ProduktZahlungFENutzer(ID),
Aktiv INT NOT NULL,
LetzterLogin datetime NOT NULL DEFAULT GETDATE(),
BENutzerID int NOT NULL
constraint FENutzer_BENutzer
foreign key references BENutzer(BENutzerID),
auth_id int not null
constraint FENutzer_auth
foreign key references auth2(id)
)
Please help
You have established a reference
FHAngehörigeID INT NOT NULL IDENTITY(1,1) PRIMARY KEY Constraint fhA_feN
REFERENCES FENutzer(FENutzerID),
This means that you need a record in your table FENutzer.FENutzerID that match FHAngehörigeID, in this case you cannot use IDENTITY
Your construction makes no sense - this way, you're creating two tables that depend on each other, at the primary key level - so you would have to have an existing entry in FENutzer in order to insert a new row into FHAngehörige, and this at the same time is only possible if you already have an existing row in FHAngehörige to insert the row in FEnutzer.....
You need to clean this up:
both tables need a primary key and the int identity(1,1) is a very good choice
one of the tables must reference the other, but with a normal foreign key attribute - not on the primary key.....
Since you've not given any indication as to which of the tables is the "main" table and which the "child/auxiliary" table, I'm just picking one over the other - so your table structure should be something like:
CREATE TABLE dbo.FHAngehoerige
(
FHAngehoerigeID INT NOT NULL IDENTITY(1,1)
CONSTRAINT PK_FHAngehoerige PRIMARY KEY CLUSTERED,
Name VARCHAR(50) NOT NULL,
Fachbereich INT NOT NULL,
Email VARCHAR(50) NOT NULL UNIQUE
)
CREATE TABLE dbo.FENutzer
(
-- define the PK for the table
FENutzerID INT IDENTITY(1,1) NOT NULL
CONSTRAINT PK_FENutzer PRIMARY KEY CLUSTERED,
-- define the **foreign key** to the main table
FHAngehoerigeID INT NOT NULL
CONSTRAINT FK_FENutzer_FHAngehoerige
FOREIGN KEY REFERENCES dbo.FHAngehoerige(FHAngehoerigeID),
Aktiv INT NOT NULL,
LetzterLogin datetime NOT NULL DEFAULT GETDATE(),
BENutzerID int NOT NULL
constraint FENutzer_BENutzer
foreign key references BENutzer(BENutzerID),
auth_id int not null
constraint FENutzer_auth
foreign key references auth2(id)
)
Also: I would strongly recommend (from my own personal, bad experience) to AVOID any special characters like umlauts or accents or anything like that in table and column names.....

How can I move data from one column of a parent into a new child table?

I have two tables: WordForm and WordDefinition:
CREATE TABLE [dbo].[WordForm] (
[WordFormId] VARCHAR (20) NOT NULL,
[WordId] VARCHAR (20) NOT NULL,
[Primary] BIT DEFAULT ((0)) NOT NULL,
[PosId] INT NOT NULL,
-- I want to move text data from this column into
-- the WordDefinition table column called Definition
-- and then I will remove the column from here later.
[Definition] VARCHAR (MAX) NULL,
[Sample] VARCHAR (MAX) NULL,
[Synonym] VARCHAR (100) NULL,
PRIMARY KEY CLUSTERED ([WordFormId] ASC),
CONSTRAINT [FK_WordFormPos] FOREIGN KEY ([PosId]) REFERENCES [dbo].[Pos] ([PosId]),
CONSTRAINT [FK_WordFormWord] FOREIGN KEY ([WordId]) REFERENCES [dbo].[Word] ([WordId])
);
CREATE TABLE [dbo].[WordDefinition]
(
[WordDefinitionId] INT IDENTITY (1, 1) NOT NULL,
[WordFormId] VARCHAR (20) NOT NULL,
[Definition] VARCHAR (MAX) NOT NULL
CONSTRAINT [PK_WordDefinition] PRIMARY KEY CLUSTERED ([WordDefinitionId] ASC),
)
Initially the WordForm table was created to hold single definitions but now I realize there can be more definitions for each WordForm.
To implement this I added the WordDefinition table. One WordForm row to Many WordDefinition rows.
But now what I need to do is to go through the WordForm table and add an entry with the original definition (from WordForm) and copy this into the WordDefinition table for each row in WordForm.
Is this something I could do only with SQL or would I need to use a cursor. Any help and advice on how to do this would be much appreciated.
I think you can just use 1 query INSERT INTO SELECT to do this, something like this:
INSERT INTO [dbo].[WordDefinition]
SELECT [WordFormId], [Definition]
FROM [dbo].[WordForm]
After that you can delete the old column Definition from WordForm.

SQL Server error - Incorrect syntax for definition of the 'TABLE' constraint

T-SQL error on SQL 2008 when I run this code.
This type of question has been asked a few times in the past on Stack Overflow, and is normally to do with a comma being in the wrong place, but for the life of me I can't see what is wrong with the following SQL
CREATE TABLE IntroducerSupportLink
(
IntroducerSupportLinkId int identity,
IntroducerId nvarchar(12) not null,
SupportStaffId nvarchar(12) not null,
Status numeric(5),
SupportStaffType numeric(5),
CreatedDateTime datetime not null,
CONSTRAINT PK_IntroducerSupportLink_IntroducerSupportLinkId Primary key(IntroducerSupportLinkId),
CONSTRAINT FK_IntroducerSupportLink_IntroducerId foreign key(IntroducerId) REFERENCES Introducer(introducerId),
CONSTRAINT FK_IntroducerSupportLink_SupportStaffId foreign key(SupportStaffId) REFERENCES Introducer(introducerId),
CONSTRAINT DF_IntroducerSupportLink_CreatedDateTime DEFAULT (GETDATE())
)
It runs if the last (default) constraint is commented out
Try following,
CREATE TABLE IntroducerSupportLink
(
IntroducerSupportLinkId int identity,
IntroducerId nvarchar(12) not null,
SupportStaffId nvarchar(12) not null,
Status numeric(5),
SupportStaffType numeric(5),
CreatedDateTime datetime not null DEFAULT GETDATE(),
CONSTRAINT PK_IntroducerSupportLink_IntroducerSupportLinkId Primary key(IntroducerSupportLinkId),
CONSTRAINT FK_IntroducerSupportLink_IntroducerId foreign key(IntroducerId) REFERENCES Introducer(introducerId),
CONSTRAINT FK_IntroducerSupportLink_SupportStaffId foreign key(SupportStaffId) REFERENCES Introducer(introducerId)
)
You can also do this thing inline
CreatedDateTime datetime not null CONSTRAINT "constraints_CreatedDateTime" DEFAULT GETDATE(),
You can not define DEFAULT constraints at table level by design, see here
You didn't "attach" the last constraint to any column.
To do that with a DEFAULT constraint, you must use it on the column definition itself (see full syntax here)
Try below code..
create TABLE IntroducerSupportLink5
(
IntroducerSupportLinkId int identity,
IntroducerId nvarchar(12) not null,
SupportStaffId nvarchar(12) not null,
Status numeric(5),
SupportStaffType numeric(5),
CreatedDateTime datetime not null constraint DF_IntroducerSupportLink_CreatedDateTime DEFAULT (GETDATE()),
CONSTRAINT PK_IntroducerSupportLink_IntroducerSupportLinkId Primary key(IntroducerSupportLinkId),
CONSTRAINT FK_IntroducerSupportLink_IntroducerId foreign key(IntroducerId) REFERENCES Introducer(introducerId),
CONSTRAINT FK_IntroducerSupportLink_SupportStaffId foreign key(SupportStaffId) REFERENCES Introducer(introducerId)
)

Resources