I am using Microsoft SQL Server and trying to add a foreign key to the "Orders" table that references the primary key in my "Customer" table. I keep getting this message:
Msg 1769, Level 16, State 1, Line 28
Foreign key 'orders_customerid_fk' references invalid column 'CustomerID' in referencing table 'Orders'.
Msg 1750, Level 16, State 0, Line 28
Could not create constraint or index. See previous errors.
CREATE TABLE Customer
(
CustomerID INT NOT NULL PRIMARY KEY,
fName varchar(40),
lName varchar(40),
City varchar(40),
Country varchar(40),
Phone varchar(20)
);
CREATE TABLE Supplier
(
SupplierID INT NOT NULL PRIMARY KEY,
CompanyName varchar(40),
ContactName varchar(50),
ContactTitle varchar(40),
City varchar(40),
Country varchar(40),
Phone varchar(30),
Fax varchar(30),
);
CREATE TABLE Orders
(
OrderID INT NOT NULL PRIMARY KEY,
OrderDate datetime,
OrderNumber varchar(10),
TotalAmount decimal(12,2)
);
ALTER TABLE Orders
ADD CONSTRAINT Orders_CustomerID_FK
FOREIGN KEY(CustomerID) REFERENCES Customer(CustomerID);
You are missing the column that should receive the constrain of FK.
ALTER TABLE Orders
ADD CustomerID INT NULL; /*Adds a new int column existing rows will be
given a NULL value for the new column*/
Or
ALTER TABLE Orders
ADD CustomerID INT NOT NULL DEFAULT(0);
And then you can
ALTER TABLE Orders
ADD CONSTRAINT Orders_CustomerID_FK
FOREIGN KEY(CustomerID)
REFERENCES Customer(CustomerID)
;
THIS IS NOT DUPLICITY
I am NOT setting value to identity column!
I cant add value in my Table. I think all set good but this error keeps comming:
"Cannot insert explicit value for identity column in table 'MainQueue'
when IDENTITY_INSERT is set to OFF."
My table:
CREATE TABLE [dbo].[MainQueue] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Created] DATETIME NOT NULL,
[IdOffice] INT NOT NULL,
[IdCategory] INT NOT NULL,
[StartProcessTime] DATETIME NULL,
[EndProcessTime] DATETIME NULL,
[IdUser] INT NULL,
[Sms] BIT CONSTRAINT [DF__MainQueue__Sms__412EB0B6] DEFAULT ((0)) NOT NULL,
[OrderNumber] INT NOT NULL,
[IdSms] INT NULL,
[UserWindowNumber] INT NULL,
CONSTRAINT [PK__MainQueu__3214EC0783954F32] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_MainQueue_Category] FOREIGN KEY ([IdCategory]) REFERENCES [dbo].[Category] ([Id]),
CONSTRAINT [FK_MainQueue_Office] FOREIGN KEY ([IdOffice]) REFERENCES [dbo].[Office] ([Id]),
CONSTRAINT [FK_MainQueue_User] FOREIGN KEY ([IdUser]) REFERENCES [dbo].[User] ([Id]),
CONSTRAINT [FK_MainQueue_SmsQueue] FOREIGN KEY ([IdSms]) REFERENCES [dbo].[SmsQueue] ([Id])
);
My code for adding:
var queueItem = new MainQueue();
queueItem.IdOffice = officeId;
queueItem.IdCategory = categoryId;
queueItem.Created = DateTime.Now;
queueItem.OrderNumber = orderNum;
dc.MainQueues.InsertOnSubmit(queueItem);
dc.SubmitChanges();
THIS IS NOT DUPLICITY
I am NOT setting value to identity column!
Your described ID column is an autoincrement identity column, that means you cannot pass any explicit value for the ID, after an insert the DBS will do fill the ID. Remove the ID column in your Insert method and do not pass a parameter for the Id when calling your method.
If you really need to insert an explicit value for the ID, either make the column not an IDENTITY, instead primary or turn IDENTITY INSERT OFF before you call the insert and turn in back on afterwards.
I met an error in an SQL command when trying to create a table in SQL. Below is my command:
CREATE TABLE Registration
(
registrationID varchar2(5) NOT NULL CONSTRAINT registrationID PRIMARY KEY,
competitionID varchar2(5) NOT NULL CONSTRAINT competitionID REFERENCES Competition(competitionID),
competitorID varchar2(5) NOT NULL CONSTRAINT competitorID REFERENCES Competitor(competitorID),
categoryType varchar2(6) NOT NULL,
entryFeeStatus char(1) NOT NULL,
creditCardNumber number(16),
datePaid date
);
My competitionID is primary key of Competition table.
My competitorID is primary key of Competitor table.
The error shown is:
Error report -
SQL Error: ORA-02264: name already used by an existing constraint
02264. 00000 - "name already used by an existing constraint"
*Cause: The specified constraint name has to be unique.
*Action: Specify a unique constraint name for the constraint.
May I know what I should change in my statement? Thank you.
Below are the Competition and Competitor tables that I created:
CREATE TABLE Competition
(
competitionID varchar2(5) NOT NULL CONSTRAINT competitionID PRIMARY KEY,
timePlanned date NOT NULL,
country varchar2(50) NOT NULL,
city varchar2(50),
address varchar2(50),
entryFee number(4) NOT NULL
);
CREATE TABLE Competitor
(
competitorID varchar2(5) NOT NULL CONSTRAINT competitorID PRIMARY KEY,
firstName varchar2(9) NOT NULL,
lastName varchar2(9) NOT NULL,
dateOfBirth date NOT NULL,
nationality varchar2(12),
gender varchar2(1) NOT NULL,
lifetimeRanking number(6),
totalPrizeMoney number(6)
);
You mixed up the two different ways to specify foreign keys. And had an extra comma.
CREATE TABLE Registration
(
registrationID varchar2(5) NOT NULL CONSTRAINT registrationID PRIMARY KEY,
competitionID varchar2(5) NOT NULL CONSTRAINT competitionIDfk REFERENCES Competition(competitionID),
competitorID varchar2(5) NOT NULL CONSTRAINT competitorIDfk REFERENCES Competitor(competitorID)
)
Foreign keys can either be specified per column:
columnname datatype CONSTRAINT constraintname REFERENCES tablename [ (column) ]
Or per table:
CONSTRAINT constraintname FOREIGN KEY (column-list) REFERENCES tablename [ (column-list) ]
BOOLEAN is not valid SQL type. Use NUMBER(1) with 0 and 1, CHAR(1) or VARCHAR2(1) with 'Y' and 'N' values or other surrogate representation.
Have a situation
2 different tables
CREATE TABLE albums(
album_id int identity (10,5) not null,
album_title varchar (40) not null,
album_itunes_price decimal DEFAULT 12.99 not null,
album_group_id int not null,
album_copies_sold int DEFAULT 0 null
)
go
CREATE TABLE SONGS
(song_id int identity (5,5) not null,
song_title varchar (50) not null,
song_group_id int not null,
song_album_id int null,
song_time time not null,
song_itunes_cost money not null )
GO
ALTER TABLE songs
ADD
CONSTRAINT pk_song_id
PRIMARY KEY (song_id),
CONSTRAINT fk_song_album_id
FOREIGN KEY (song_album_id)
REFERENCES albums(album_id),
CONSTRAINT fk_song_group_id
FOREIGN KEY (song_group_id)
REFERENCES groups(group_id)
go
create a check constraint on songs table called ck_songs_itunes_cost
The songs can be free but they can never be more than the album_itunes_price.
How do i create this constraint been working on it for 12 hours nothing is working.
I think the below is what you are expecting:
create a function that returns the values from album table:
Create function [dbo].[MaxValue]()
returns decimal
as
begin
declare #retval int
select #retval=MAX(album_itunes_price) from dbo.albums
return #retval
end;
Then create check constraint in songs which can get the value from albums table, because we can't use subquery in check constraint.
alter table dbo.songs
add constraint ck_songs_itunes_cost
check (songscolumn < dbo.MaxValue())
Make use of it based on your need.
I'm pretty new to databases and I have this assignment that I've completed where I had to look at a merged Entity Relationship Diagram and then create Drop Tables, Tables (with constraints and identity's), Alterations and Indexes. I'm pretty sure I've coded everything correctly but the only area I'm a little unsure about, it's how to test that the database will actually function when executing it. My instructor gave me a TestData.sql file that I just have to refer to the database and then execute and it should insert all the data into the tables and drop everything correctly. I have it all hooked up properly on SQL Server Management Studio but I forget what steps I should be taking in order to test the proper execution of the tables. I'll post some of my code so you guys can take a look. Any information regarding this issue would be greatly appreciated!
Also, when it says in the Test Data SQL code "IMPORTANT! If you need to run this script more than once you must drop and recreate your tables first to reset the identity properties." --Does this mean that if I run into any errors while trying to execute the test data, I will have to execute the DROP TABLES first and then maybe copy and paste all the TABLES back into the Database file? I don't actually have to manually type all the TABLES again, just need to re-enter them as "new" so the system will kind of reset it's identity properties?
If you guys need me to post more of the code for clarification, just let me know. Thanks for taking the time to read this :)
Update: I'm getting 2 error messages when trying to execute the TestData script: "Invalid object name 'SaleDetail'." and "Invalid object name 'Author'." I've also provided the rest of the code from my Database script file for you to take a look at. I'm almost certain everything is correct.
Database Tables Code (this is the complete code script)
USE Lab2A_BooksGalore
GO
/*------ Drop Table Statements ------*/
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'SaleDetail')
DROP TABLE SaleDetail
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'AuthorTitle')
DROP TABLE AuthorTitle
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Title')
DROP TABLE Title
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Publisher')
DROP TABLE Publisher
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Category')
DROP TABLE Category
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Author')
DROP TABLE Author
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Sale')
DROP TABLE Sale
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Employee')
DROP TABLE Employee
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Customer')
DROP TABLE Customer
/*------- Create Table Statements -------*/
CREATE TABLE Customer
(
CustomerNumber int
CONSTRAINT PK_Customer_CustomerNumber
PRIMARY KEY
IDENTITY (1, 1) NOT NULL,
LastName varchar(30) NOT NULL,
FirstName varchar(30) NOT NULL,
[Address] varchar(40) NULL,
City varchar(30) NULL,
Province char(2)
CONSTRAINT DF_Customer_Province
DEFAULT ('AB') NULL,
PostalCode char(6)
CONSTRAINT CK_Customer_PostalCode
CHECK (PostalCode LIKE '[A-Z][0-9][A-Z][0-9][A-Z][0-9]')
NULL,
HomePhone char(10)
)
CREATE TABLE Employee
(
EmployeeNumber int
CONSTRAINT PK_Employee_EmployeeNumber
PRIMARY KEY
IDENTITY (300, 1) NOT NULL,
[SIN] char(9) NOT NULL,
LastName varchar(30) NOT NULL,
FirstName varchar(30) NOT NULL,
[Address] varchar(40) NULL,
City varchar(20) NULL,
Province char(2)
CONSTRAINT DF_Employee_Province
DEFAULT ('AB') NULL,
PostalCode char(6)
CONSTRAINT CK_Employee_PostalCode
CHECK (PostalCode LIKE '[A-Z][0-9][A-Z][0-9][A-Z][0-9]')
NULL,
HomePhone char(10) NULL,
WorkPhone char(10) NULL,
Email varchar(40) NULL,
)
CREATE TABLE Sale
(
SaleNumber int
CONSTRAINT PK_Sale_SaleNumber
PRIMARY KEY
IDENTITY (3000, 1) NOT NULL,
SaleDate datetime NOT NULL,
CustomerNumber int
CONSTRAINT FK_Sale_CustomerNumber_Customer_CustomerNumber
FOREIGN KEY REFERENCES Customer(CustomerNumber)
NOT NULL,
EmployeeNumber int
CONSTRAINT FK_Sale_EmployeeNumber_Employee_EmployeeNumber
FOREIGN KEY REFERENCES Employee(EmployeeNumber)
NOT NULL,
Subtotal money
CONSTRAINT CK_Sale_Subtotal
CHECK (Subtotal <= Total) NOT NULL,
GST money NOT NULL,
Total money
CONSTRAINT CK_Sale_Total
CHECK (Total >= Subtotal) NOT NULL,
)
CREATE TABLE Author
(
AuthorCode int
CONSTRAINT PK_Author_AuthorCode
PRIMARY KEY
IDENTITY (100, 1) NOT NULL,
LastName varchar(30) NOT NULL,
FirstName varchar(30) NOT NULL,
)
CREATE TABLE Category
(
CategoryCode int
CONSTRAINT PK_Category_CategoryCode
PRIMARY KEY
IDENTITY (1, 1) NOT NULL,
[Description] varchar(40) NOT NULL,
)
CREATE TABLE Publisher
(
PublisherCode int
CONSTRAINT PK_Publisher_PublisherCode
PRIMARY KEY
IDENTITY (200, 1) NOT NULL,
[Name] varchar(40) NOT NULL,
)
CREATE TABLE Title
(
ISBN char(10)
CONSTRAINT PK_Title_ISBN
PRIMARY KEY NOT NULL,
Title varchar(40) NOT NULL,
SuggestedPrice smallmoney
CONSTRAINT DF_Title_SuggestedPrice
DEFAULT (0) NOT NULL,
NumberInStock smallint
CONSTRAINT CK_Title_NumberInStock
CHECK (NumberInStock >= 0)
CONSTRAINT DF_Title_NumberInStock
DEFAULT (0) NOT NULL,
PublisherCode int
CONSTRAINT FK_Title_PublisherCode_Publisher_PublisherCode
FOREIGN KEY REFERENCES Publisher(PublisherCode)
NOT NULL,
CategoryCode int
CONSTRAINT FK_Title_CategoryCode_Category_CategoryCode
FOREIGN KEY REFERENCES Category(CategoryCode)
NOT NULL,
)
CREATE TABLE AuthorTitle
(
ISBN char(10)
CONSTRAINT FK_AuthorTitle_ISBN_Title_ISBN
FOREIGN KEY REFERENCES Title(ISBN)
NOT NULL,
AuthorCode int
CONSTRAINT FK_AuthorTitle_AuthorCode_Author_AuthorCode
FOREIGN KEY REFERENCES Author(AuthorCode)
NOT NULL,
)
CREATE TABLE SaleDetail
(
SaleNumber int
CONSTRAINT FK_SaleDetail_SaleNumber_Sale_SaleNumber
FOREIGN KEY REFERENCES Sale(SaleNumber)
NOT NULL,
ISBN char(10)
CONSTRAINT FK_SaleDetail_ISBN_Title_ISBN
FOREIGN KEY REFERENCES Title(ISBN)
NOT NULL,
SellingPrice money NOT NULL,
Quantity int NOT NULL,
Amount money NOT NULL,
)
/*----------------- Alter Table Statements --------------------*/
---1) Add a char(10) attribute named WorkPhone to the Customer Table
ALTER TABLE Customer
ADD WorkPhone char(10) NULL
GO
---2) Add a varchar(30) attribute named Email to the Customer Table
ALTER TABLE Customer
ADD Email varchar(30) NULL
GO
---3) Add a constraint to make sure the correct format is followed for the Email attribute
ALTER TABLE Customer
ADD CONSTRAINT CK_Customer_Email
CHECK (Email LIKE '[a-z, 0-9][a-z, 0-9][a-z, 0-9]%#[a-z, 0-9][a-z, 0-9][a-z, 0-9]%.[a-z, 0-9][a-z, 0-9]%')
--- Match For: b 8 l # g v t . c a
GO
---4) Add a char(1) attribute named Active that's required for the Employee Table
ALTER TABLE Employee
ADD Active char(1) NOT NULL
GO
---5) Add a constraint to make sure the default character is used for the Active attribute
ALTER TABLE Employee
ADD CONSTRAINT DF_Employee_Active
DEFAULT ('y')
GO
/*------------------ Foreign Key Index Statements -----------------*/
CREATE NONCLUSTERED INDEX IX_Sale_CustomerNumber
ON Sale (CustomerNumber)
CREATE NONCLUSTERED INDEX IX_Sale_EmployeeNumber
ON Sale (EmployeeNumber)
CREATE NONCLUSTERED INDEX IX_Title_PublisherCode
ON Title (PublisherCode)
CREATE NONCLUSTERED INDEX IX_Title_CategoryCody
ON Title (CategoryCode)
CREATE NONCLUSTERED INDEX IX_AuthorTitle_ISBN
ON AuthorTitle (ISBN)
CREATE NONCLUSTERED INDEX IX_AuthorTitle_AuthorCode
ON AuthorTitle (AuthorCode)
CREATE NONCLUSTERED INDEX IX_SaleDetail_SaleNumber
ON SaleDetail (SaleNumber)
CREATE NONCLUSTERED INDEX IX_SaleDetail_ISBN
ON SaleDetail (ISBN)
GO
Test Data Code(this is only a snippet being this script is 100% accurate - provided by instructor)
USE Lab2A_BooksGalore
GO
--Lab 2 insert script
--IMPORTANT! If you need to run this script more than once you must drop and recreate your tables first to reset the identity properties.
--Delete existing data in the tables, if there is any
Delete From SaleDetail
Delete From Sale
Delete From AuthorTitle
Delete From Title
Delete From Employee
Delete From Customer
Delete From Category
Delete From Publisher
Delete From Author
Go
Insert into Author
(LastName, FirstName)
Values
('Smith', 'Sammy'),
('Greens', 'George'),
('Jones', 'Johnny'),
('Davidson', 'David'),
('Robertson', 'Rob'),
('Abbots', 'Abe'),
('Bakers', 'Bob'),
('Caters', 'Clem'),
('Semenko', 'Dave'),
('Franky', 'Fran'),
('Horton', 'Harry'),
('Kelly', 'Kevin'),
('Lambert', 'Larry'),
('Johnson', 'Jon'),
('Anderson', 'Ander'),
('Peterson', 'Peter'),
('Jensen', 'Jens'),
('Issacsen', 'Issac')
Insert into Publisher
(Name)
Values
('Addison Westley'),
('SAMS'),
('Harlequin'),
('Self Publish Inc'),
('Microsoft Press'),
('Jones and Bartlett'),
('WROX'),
('West'),
('Premier')
Insert into Category
(Description)
Values
('Computers'),
('Business'),
('Human Relation'),
('Electronics'),
('Designs'),
('Miscellaneous'),
('Media Design'),
('Information Technologies')