Check Constraint that references another table - sql-server

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.

Related

default constraint not firing

added Default Constraint on a Foreign key column for default value so if the user does not supply value default value should be inserted. but instead of firing constraint, it shows Column name or number of supplied values does not match table definition.
--Table--
create table tblperson(
Id int not null,
Name nvarchar(50) not null,
Email nvarhcar(50) not null,
GenderId int
);
--tblGender--
Create Table tblGender(
ID int Not Null Primary Key,
Gender nvarchar(50)
);
--Add foreign Key--
Alter table tblPerson
add constraint tblPerson_GenderId_FK FOREIGN KEY (GenderId) references tblGender(ID)
--Default Constraint--
ALTER TABLE tblPerson
ADD CONSTRAINT DF_tblPerson_GenderId
DEFAULT 1 FOR GenderId
--Insert Statement--
insert into tblperson values(5,'Jake','j#j.com')
The answer to your question is:
insert into tblperson(Id, Name, Email) values(1,'Jake','j#j.com');
Most of people forget to write the columns names, you should always be carful of the columns names and the number of supplied values.
BTW, fix the typo in this line:
Email nvarhcar(50) not null,
it should be:
Email nvarchar(50) not null,

How can I change the value of a primary key of a table to be a random number?

I have this table:
CREATE TABLE [dbo].[Word] (
[WordId] INT NOT NULL,
[Name] VARCHAR (20) NOT NULL,
[StatusId] INT DEFAULT ((1)) NULL,
[Syllables] VARCHAR (20) NULL,
[Ascii] AS (ascii([Name])) PERSISTED,
[CategoryId] INT DEFAULT ((1)) NOT NULL,
[GroupId] INT DEFAULT ((1)) NOT NULL,
[LessonId] INT DEFAULT ((1)) NOT NULL,
[CreatedBy] INT DEFAULT ((1)) NOT NULL,
[CreatedDate] DATETIME DEFAULT (getdate()) NOT NULL,
[ModifiedBy] INT DEFAULT ((1)) NOT NULL,
[ModifiedDate] DATETIME DEFAULT (getdate()) NOT NULL,
[Version] ROWVERSION NULL,
PRIMARY KEY CLUSTERED ([WordId] ASC),
CONSTRAINT [FK_WordLesson] FOREIGN KEY ([LessonId]) REFERENCES [dbo].[Lesson] ([LessonId]),
CONSTRAINT [FK_WordWordCategory] FOREIGN KEY ([CategoryId]) REFERENCES [dbo].[WordCategory] ([WordCategoryId]),
CONSTRAINT [FK_WordWordGroup] FOREIGN KEY ([GroupId]) REFERENCES [dbo].[WordGroup] ([WordGroupId])
);
GO
CREATE NONCLUSTERED INDEX [Word_Category_IX]
ON [dbo].[Word]([CategoryId] ASC);
GO
CREATE NONCLUSTERED INDEX [Word_Group_IX]
ON [dbo].[Word]([GroupId] ASC);
GO
CREATE NONCLUSTERED INDEX [Word_Lesson_IX]
ON [dbo].[Word]([LessonId] ASC);
How can I change the value of WordId to be a random number that is between 1 and the maximum value of the INT column?
Note that I understand there's a possibility of the random number being used twice but it's test data so I am not too concerned about that.
I'm going to suggest a different approach to this than the route you are currently going down.
Just use an identity column, it's inbuilt and because this field is the Primary Key you need to ensure you don't get duplicates. The code would look like this.
CREATE TABLE [dbo].[Word] (
[WordId] INT IDENTITY(1,1) NOT NULL,
It will give you a value starting with 1 that increments by 1 each time a new row of data is entered.
Also, looking at your code, you've got the field StatusId as nullable but with a default value, are you sure that you don't want this as a NOT NULL field?
For information, you can use this calculation to get a random number less than a given int value;
DECLARE #RandomInt int; SET #RandomInt = 42
SELECT
#RandomInt Number
,ROUND(RAND()*#RandomInt,0) RandomLessThanInt
You'll get an answer like this;
Number RandomLessThanInt
42 15
It will obviously change every time it's run. You'd have to ensure that the number didn't already exist otherwise you will be attempting to violate the PK constraint and the insert will fail.
If you already have the table populated with data then you could do this
UPDATE TableName
SET FieldName = ROUND(RAND()*FieldName,0)

WPF Cant insert into table - (I AM NOT SETTING VALUE INTO IDENTITY COULMN)

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.

Foreign key contraints in a table on two columns referncing a same table

I have a table Item master, in which i have a primary key as item code
tbl_item_master
Itm_code int PK
Bill of material(tbl_Bom)
child_id int
parent_id int
I have another table of bill of material(tbl_bom) in which there are 2 columns of parent and child which are having their values which is nothin but primary key of item master. I.e parent and child id in BOM are from Item Master's primary key. Follwoing is my script that I am using to apply foreign key on child and parent .
CREATE TABLE dbo.BOM_MASTER
(
BOM_SrNo INT CONSTRAINT DF_BOM_MASTER_BOM_SrNo DEFAULT ((0)) NOT NULL,
BOM_Key INT NOT NULL,
PD_Key INT,
BOM_Level INT,
BOM_Parent_Code VARCHAR (50),
BOM_Child_Code VARCHAR (50),
BOM_UOM INT,
BOM_Qty DECIMAL (14, 2),
BOM_Final_Version INT,
BOM_ItemDimension_Applicable BIT,
BOM_MatType INT CONSTRAINT DF__BOM_MASTE__BOM_M__192BAC54 DEFAULT ((0)) NOT NULL,
CONSTRAINT FK_BOM_MASTER_Project_Details_Master FOREIGN KEY (PD_Key) REFERENCES dbo.Project_Details_Master (PD_Key),
CONSTRAINT FK_BOM_MASTER_tbl_itm_master FOREIGN KEY (BOM_Parent_Code) REFERENCES tbl_itm_master (BSL_COST_ITEM_Item_SAP_Code),
CONSTRAINT FK_BOM_MASTER_tbl_itm_master FOREIGN KEY (BOM_Child_Code) REFERENCES tbl_itm_master (BSL_COST_ITEM_Item_SAP_Code)
)
GO
and I am getting the following error
Cannot create two constraints named 'FK_BOM_MASTER_tbl_itm_master'. Duplicate constraint names are not allowed. Severity 16
If you add newlines, the issue becomes apparent.
CREATE TABLE dbo.BOM_MASTER
(
BOM_SrNo INT CONSTRAINT DF_BOM_MASTER_BOM_SrNo DEFAULT ((0)) NOT NULL,
BOM_Key INT NOT NULL,
PD_Key INT,
BOM_Level INT,
BOM_Parent_Code VARCHAR (50),
BOM_Child_Code VARCHAR (50),
BOM_UOM INT,
BOM_Qty DECIMAL (14, 2),
BOM_Final_Version INT,
BOM_ItemDimension_Applicable BIT,
BOM_MatType INT CONSTRAINT DF__BOM_MASTE__BOM_M__192BAC54 DEFAULT ((0)) NOT NULL,
CONSTRAINT FK_BOM_MASTER_Project_Details_Master FOREIGN KEY (PD_Key) REFERENCES dbo.Project_Details_Master (PD_Key),
CONSTRAINT FK_BOM_MASTER_tbl_itm_master FOREIGN KEY (BOM_Parent_Code) REFERENCES tbl_itm_master (BSL_COST_ITEM_Item_SAP_Code),
CONSTRAINT FK_BOM_MASTER_tbl_itm_master FOREIGN KEY (BOM_Child_Code) REFERENCES tbl_itm_master (BSL_COST_ITEM_Item_SAP_Code)
)
GO
The last 2 are named identically. It is also clear there are other naming issues. What is DF__BOM_MASTE__BOM_M__192BAC54? Will future users of the table be able to gleem anything from this naming?

What is the proper procedure when trying to test your database in SQL?

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

Resources