What does the constraint mean? - sql-server

I am new to SQL and I am trying to create a table with a constraint but I have not used the constrant before and I am not actually certain what this constraint does uc_ID on PId, LastName?
I want to create a constraint that will only allow alpha numeric values in a column?
Code:
CREATE TABLE Persons
(
PId int identity(1,1) NOT NULL,
LastName varchar(25) NOT NULL,
FirstName varchar(25) NOT NULL,
Address1 varchar(25) NOT NULL,
City varchar(25) NOT NULL
CONSTRAINT uc_ID UNIQUE (PId,LastName)
)
CREATE TABLE E
(
PId int identity(1,1) NOT NULL,
LastName varchar (25) NOT NULL,
FirstName varchar (25) NOT NULL,
Address1 varchar (25) NOT NULL,
City varchar (25) NOT NULL
CONSTRAINT OnlyAlphanumeric CHECK ([FirstName] NOT LIKE '%[^A-Z0-9]%')
)
Another Example (is not):
CREATE TABLE EEE
(
PId int identity(1,1) NOT NULL,
FirstName varchar (50) NOT NULL,
CONSTRAINT CHECK ([FirstName] LIKE '%[A-Za-z]%')
)

Means that the combination of Pid + LastName must be unique.
Since Pid is an identity, in normal circumstances it cannot be duplicated, so that constraint seems somehow redudant.

Try:
ALTER TABLE TableName ADD CONSTRAINT Only_Characters_And_Numbers CHECK ColumnName NOT LIKE '%[^A-Z0-9 ]%'

If you want a constraint that allows only alphanumeric characters in a column you can use this (for example for FirstName:
ALTER TABLE [Persons] ADD CONSTRAINT OnlyAlphanumeric CHECK ([FirstName] NOT LIKE '%[^A-Z0-9 ]%')
Disclaimer: taken from here (and tested).
If you want the constraint to be added when the table is created:
CREATE TABLE Persons
(
PId int identity(1,1) NOT NULL,
LastName varchar(25) NOT NULL,
FirstName varchar(25) NOT NULL,
Address1 varchar(25) NOT NULL,
City varchar(25) NOT NULL
CONSTRAINT OnlyAlphanumeric CHECK ([FirstName] NOT LIKE '%[^A-Z0-9 ]%')
)
Note that constraint names are unique per database.
Alternatively, you can create an AFTER INSERT and AFTER UPDATE trigger to make this validation, but a constraint works just fine in this case.

Related

Postgresql Trying to implement One-To-Many

this is my first hands-on experience with Sql and I'm trying to construct One-To-Many relationship, here is the SQL code:
create table car (
id SERIAL PRIMARY KEY,
make VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
price NUMERIC(19, 2) NOT NULL
);
create table person (
id BIGSERIAL NOT NULL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
gender VARCHAR(7) NOT NULL,
email VARCHAR(100),
date_of_birth DATE NOT NULL,
country_of_birth VARCHAR(50) NOT NULL,
cars_owning INT[] REFERENCES car(id)
);
and I get this error:
Key columns "cars_owning" and "id" are of incompatible types: integer[] and integer.
Here is the model a person can have many cars but each car have only one owner
typically (as a good general rule of thumb) the many refers to the one. not the other way around as you have tried.
So, alter the schema as:
create table car (
id SERIAL PRIMARY KEY,
make VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
price NUMERIC(19, 2) NOT NULL,
owner_id BIGINT FOREIGN KEY REFERENCES person(id)
);
create table person (
id BIGSERIAL NOT NULL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
gender VARCHAR(7) NOT NULL,
email VARCHAR(100),
date_of_birth DATE NOT NULL,
country_of_birth VARCHAR(50) NOT NULL
);
If you need to get the list of cars owned by a person, use this select statement
SELECT person.id, ARRAY_AGG(car.id) owns_car_ids
FROM person
LEFT JOIN car ON person.id = car.owner_id
GROUP BY 1

What's the proper way to create these tables?

I'm reverse engineering a script that creates a payroll database from my textbook. I'm rebuilding it into a library management system instead. To start I've drawn out a diagram of the tables/columns and their relationships here. Now following the script from the textbook I use the authors technique to create all the tables except for the BooksIssued table and InvoiceItems table. This is my code
USE master
GO
/******Check to see if database exists******/
IF DB_ID('SET2133810') IS NOT NULL
DROP DATABASE SET2133810
GO
/******Object: Database SET2133810******/
CREATE DATABASE SET2133810
GO
USE SET2133810
GO
/******Object: table*****/
CREATE TABLE VendorsList(
VendorID int IDENTITY(1,1) NOT NULL,
VendorName varchar(50) NOT NULL,
VendorPhone varchar(50) NULL,
VendorContactLName varchar(50) NULL,
VendorContactFName varchar(50) NULL,
VendorAddress varchar(50) NULL,
VendorCity varchar(50) NOT NULL,
VendorState char(2) NOT NULL,
VendorZipCode varchar(20) NOT NULL,
CONSTRAINT PK_VendorsList PRIMARY KEY CLUSTERED (
VendorID ASC
)
)
GO
/******Object: Table*****/
CREATE TABLE InvoicesList(
InvoiceID int IDENTITY(1,1) NOT NULL,
VendorID int NOT NULL,
InvoiceNumber varchar(50) NOT NULL,
InvoiceDate smalldatetime NOT NULL,
InvoiceTotal money NOT NULL,
PaymentTotal money NOT NULL,
PaymentDate smalldatetime NULL,
CONSTRAINT PK_InvoicesList PRIMARY KEY CLUSTERED(
InvoiceID ASC
)
)
GO
/******Object: Table*****/
CREATE TABLE BookList(
BookID int IDENTITY(1,1) NOT NULL,
BookISBN varchar(50) NOT NULL,
BookTitle varchar(50) NOT NULL,
BookAuthor varchar(50) NOT NULL,
BookPublisher varchar(50) NOT NULL,
BookGenre varchar(50) NULL
CONSTRAINT PK_BookList PRIMARY KEY CLUSTERED(
BookID ASC
)
)
GO
/******Object: Table*****/
CREATE TABLE MembersList(
MemberID int IDENTITY(1,1) NOT NULL,
MemberLName varchar(50) NOT NULL,
MemberFName varchar(50) NOT NULL,
MemberAddress varchar(50) NULL,
MemberCity varchar(50) NOT NULL,
MemberState char(2) NOT NULL,
MemberZipCode varchar(20) NOT NULL,
MemberPhone varchar(50) NOT NULL,
MemberEmail varchar(50) NOT NULL,
CONSTRAINT PK_MembersList PRIMARY KEY CLUSTERED(
MemberID ASC
)
)
GO
I'm confused on how I would create these tables in the same way? Since they both depend on the other tables and the information thats already in them. I've looked around and found Join statements, but none of them were used in a way that would help me with this problem.
Following should be the order to create tables.
BookList
MemeberList
Book Issued
VendorList
InvoiceList
InvoiceItems
Invoice list shoul be created in last as it have references to vendor and invoice items and BookIssues should be created after MemberList and Book List

I am getting syntax errors and don't know how to fix them

I am getting an error
Incorrect syntax near ','
and do not know how to fix it.
I have tried rewriting the query, referencing old code, and nothing seems to work.
USE RewriteExam
GO
IF EXISTS(SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID('dbo.Vendors')
AND type IN ('U'))
BEGIN
PRINT 'Vendors table already exists, dropping it now!'
DROP TABLE Vendors
END
GO
PRINT 'Creating the "Vendors" Table'
CREATE TABLE dbo.Vendors
(
VendorID INT PRIMARY KEY,
VendorName VARCHAR(45) NOT NULL,
VendorAddress VARCHAR(45) NULL,
VendorCity VARCHAR(45) NOT NULL,
VendorState VARCHAR(45) NOT NULL,
VendorZipCode VARCHAR(45) NOT NULL,
VendorPhone VARCHAR(45) NULL,
VendorContactLName VARCHAR(7) NULL,
VendorContactFName VARCHAR(14) NULL,
AcountNo INT NOT NULL,
ModifiedDate SMALLDATETIME NOT NULL,
AccountNo INT FOREIGN KEY,
CONSTRAINT PK_Vendors_VendorID
PRIMARY KEY (VendorID)
--REFERENCES Vendors (VendorID)
);
GO
PRINT 'Creating the "GLAccounts" Table'
CREATE TABLE dbo.GLAccounts
(
AccountNo INT PRIMARY KEY,
AccountDescription VARCHAR(45) NOT NULL,
);
GO
The trouble is in the constraints. The comma after the foreign key is giving me the error as well as PRIMARY KEY (VendorID)
Just need to add the commented out part after
AccountNo INT FOREIGN KEY
and convert to
AccountNo INT FOREIGN KEY REFERENCES Vendors (VendorID)
and remove already defined constraint PRIMARY KEY (VendorID)

Foreign key reference mismatched data type error

The ArtistID column in Piece table refers to the ArtistID in the Artist table. Likewise, the LocationID column in Piece refers to LocationID in the GeographicLocation table. However, both foreign key references throw a "not the same data type as referencing column" error. What am I doing wrong?
CREATE TABLE dbo.Artist
(
ArtistID SMALLINT PRIMARY KEY IDENTITY,
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
Nationality VARCHAR(10) NULL,
BirthYear SMALLINT NOT NULL CHECK(BirthYear <= 1980),
DeathYear SMALLINT NULL,
Sex CHAR(1) NOT NULL CHECK(Sex = 'F' OR Sex = 'M')
)
CREATE TABLE dbo.Piece
(
PieceID SMALLINT PRIMARY KEY IDENTITY(1, 5),
ArtistID SMALLINT NOT NULL
FOREIGN KEY REFERENCES Artist(ArtistID),
LocationID SMALLINT NOT NULL
FOREIGN KEY REFERENCES GeographicLocation(LocationID),
CommonName VARCHAR(100) NULL,
YearProduced TINYINT NULL,
Period VARCHAR(50) NULL,
Medium VARCHAR(35) NOT NULL,
Frame VARCHAR(35) NULL,
AppraisedValue MONEY NOT NULL,
AppraiserID SMALLINT NOT NULL
FOREIGN KEY REFERENCES Appraiser(AppraiserID)
)
CREATE TABLE dbo.GeographicLocation
(
LocationID SMALLINT PRIMARY KEY IDENTITY,
Country VARCHAR(25) NOT NULL,
City VARCHAR(50) NOT NULL
)
I think you missed a table here, which is AppraiserID column in Piece table refers to the AppraiserID in the Appraisertable
So, when I execute your SQL I am getting below error:
Foreign key 'FK__Piece__Appraiser__322C6448' references invalid table 'Appraiser'.
First Create a table called Appraiser, then create Foreign key references for those column.
Below SQL I am able to create all tables and Foreign key references:
CREATE TABLE dbo.Artist
(ArtistID SMALLINT PRIMARY KEY IDENTITY,
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
Nationality VARCHAR(10) NULL,
BirthYear SMALLINT NOT NULL CHECK(BirthYear <= 1980),
DeathYear SMALLINT NULL,
Gender CHAR(1) NOT NULL CHECK(Gender = 'F' OR Gender = 'M'))
CREATE TABLE dbo.GeographicLocation
(LocationID SMALLINT PRIMARY KEY IDENTITY,
Country VARCHAR(25) NOT NULL,
City VARCHAR(50) NOT NULL)
CREATE TABLE dbo.Appraiser
(AppraiserID SMALLINT PRIMARY KEY IDENTITY(1, 5),
AppraisedValue MONEY NOT NULL,
AppraisedName VARCHAR(100) NULL)
CREATE TABLE dbo.Piece
(PieceID SMALLINT PRIMARY KEY IDENTITY(1, 5),
ArtistID SMALLINT NOT NULL,
LocationID SMALLINT NOT NULL,
CommonName VARCHAR(100) NULL,
YearProduced TINYINT NULL,
Period VARCHAR(50) NULL,
Medium VARCHAR(35) NOT NULL,
Frame VARCHAR(35) NULL,
AppraisedValue MONEY NOT NULL,
AppraiserID SMALLINT NOT NULL)
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_ArtistID FOREIGN KEY(ArtistID)
REFERENCES dbo.Artist (ArtistID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_ArtistID
GO
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_AppraiserID FOREIGN KEY(AppraiserID)
REFERENCES dbo.Appraiser (AppraiserID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_AppraiserID
GO
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_LocationID FOREIGN KEY(LocationID)
REFERENCES dbo.GeographicLocation (LocationID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_LocationID
GO

How do I use A create function that compares 2 tables and does not return an int?

I am writing a database for a website for school, in Microsoft SQL Server Express
The database has a lot of different tables and also a lot of primary keys, it is not allowed to change the table itself.
The problems is that I have 2 tables, Verkoper & Gebruiker, (sorry the names are in dutch), these are the 2 tables:
create table Verkoper (
Gebruiker char(10) not null,
Bank char(8) ,
Bankrekening int,
Controle_Optie char(10) not null,
Creditcard char(19)
constraint pk_Verkoper primary key(Gebruiker),
constraint fk_Verkoper_Gebruiker foreign key(Gebruiker)
references Gebruiker(Gebruikersnaam)
)
create table gebruiker(
Gebruikersnaam char(10) not null,
Voornaam char(10) not null,
Achternaam char (15) not null ,
Adresregel1 char(25) not null,
AdresRegel2 char(25),
Postcode char(7) not null,
Plaatsnaam char(25) not null,
Land char(15) not null,
GeboorteDag char(10) not null,
Mailbox char(25) not null,
Wachtwoord char(15)not null,
Vraag int not null,
Antwoordtekst char(20) not null,
Verkoper char(4) not null,
constraint pk_gebruiker primary key(Gebruikersnaam),
constraint fk_Gebruiker_Vraag foreign key(Vraag)
references Vraag(Vraagnummer)
)
I wanna check if gebruiker.Verkoper = 'wel'(yes) or 'niet'(no). If gebruiker.verkoper = 'niet' then you should not be allowed to add it to the verkoper table.
So in short 2 tables gebruiker and verkoper if you wanna add a person to Verkoper, gebruiker.verkoper has to be true.
I already tried to make a function:
Create function dbo.checkVerkoper()
RETURNS int
AS BEGIN RETURN(
select count(*)
from Verkoper
inner join gebruiker
on verkoper.gebruiker = gebruiker.gebruikersnaam
AND gebruiker.verkoper = 'wel'
)
END
go
alter table verkoper
add constraint ck_VerkoperGebruiker
check(dbo.checkVerkoper () = 1 )
This does work for 1 person, but if you add more the value will be more then 1, and so the check will be false no one will be add, if you have 4 persons and 3 are not allowed and 1 is then the value is still 1 and you can still add someone to verkoper tabel.
You can write a stored Procedure
In that
Check whether your conditions are met
if met, then Do the insert(s)

Resources