Make a column required if other column is of certain value - sql

What I have:
CREATE TABLE [dbo].[User]
(
[id] INT NOT NULL PRIMARY KEY,
[name] VARCHAR(50) NOT NULL,
[postcode] INT NOT NULL,
[phone] INT NULL
)
What I want is that the phone number is required ONLY if the postcode is higher than 40000. If postcode is smaller than 40000, user can insert the phone number, although it is not required.
How do I do this?

You can use a check constraint:
CREATE TABLE [dbo].[User]
(
[id] INT NOT NULL PRIMARY KEY,
[name] VARCHAR(50) NOT NULL,
[postcode] INT NOT NULL,
[phone] INT NULL,
CONSTRAINT CHK_Postcode CHECK (postcode >= 4000 OR Phone IS NOT NULL)
);

This needs to be handled from the front end inserting values into the Database. Insert Query on one column based on another in the DB for the same table is not possible.

Related

How to ALTER TABLE to add CHECK constraint?

I want to ALTER my already created ZIPCODE table so that the sales_tax_applied field can never have a negative value. Here is the code for my already created table:
CREATE TABLE ZIPCODE
(
city VARCHAR(50) NOT NULL,
state CHAR(2) NOT NULL,
zipcode VARCHAR(20) NOT NULL,
sales_tax_applied DECIMAL(10,4) NOT NULL,
PRIMARY KEY (zipcode)
);
What is the code for me to be able to do this? NOTE: all fields must be NOT NULL.
Thank you
You would do:
alter table zipcode add constraint chk_zipcode_sales_tax_applied
check (sales_tax_applied >= 0);
You can also add this into the create table statement in multiple ways, such as:
CREATE TABLE ZIPCODE (
city VARCHAR(50) NOT NULL,
state CHAR(2) NOT NULL,
zipcode VARCHAR(20) NOT NULL,
sales_tax_applied DECIMAL(10,4) NOT NULL,
PRIMARY KEY (zipcode),
constraint chk_zipcode_sales_tax_applied check (sales_tax_applied >= 0)
);

Error relate SQL Server tables

I have the following problem: when we run the code, it displays the following error:
There are primary keys or candidates in the reference Ticket table
that match the list of referencing columns in foreign key '
FK__Payment__PkTicke__1A14E395
Code:
create table SystemUser
(
PkUser int identity(1,1),
UserLogin nvarchar(20) not null unique,
UserPassword nvarchar(50) not null,
UserName nvarchar(50) not null,
UserCpf nvarchar(50) not null,
UserBirth datetime not null,
UserGender nvarchar(15) not null,
AddressCep int not null,
AddressStreet nvarchar(50) not null,
AddressNumber nvarchar(20) not null,
AddressComplement nvarchar(50) not null,
AddressCity nvarchar(50) not null,
AddressState nvarchar(50) not null,
primary key(PkUser)
)
create table Attractions
(
PkAttraction integer identity(1,1) ,
AttractionName nvarchar(50) not null unique,
AttractionDate datetime not null,
AttractionDescription nvarchar(150) not null
primary key(PkAttraction)
)
create table Ticket
(
PkTicket int identity(1,1),
PkUser int not null,
PkAttraction int not null,
TicketPrice decimal not null,
primary key(PkTicket, PkUser, PkAttraction),
foreign key(PkUser) references SystemUser(PkUser),
foreign key(PkAttraction) references Attractions(PkAttraction)
)
create table Payment
(
PkPayment int identity(1,1),
PkTicket int not null,
Portion int not null,
IdTransaction nvarchar(100) not null,
Payday datetime not null,
primary key(PkPayment, PkTicket),
foreign key(PkTicket) references Ticket(PkTicket),
)
create table FormPayment
(
PkFromPayment int identity(1,1),
PkPayment int not null,
ShareValue decimal not null,
ExpirationDate datetime not null
primary key(PkFromPayment, PkPayment),
foreign key(PkPayment) references Payment(PkPayment),
)
Your Ticket table as a primary key made up from 3 columns:
create table Ticket
(
.....
primary key(PkTicket, PkUser, PkAttraction),
....
)
Any table that wants to reference that table Ticket must also provide all 3 columns for the foreign key.
You cannot reference only part of a primary key - if you want to reference it, you must have all columns that it contains - otherwise you cannot establish a FK relationship.
So you must add the PkUser and PkAttraction columns to your Payment table so that you can establish this FK relationship:
create table Payment
(
PkPayment int identity(1,1),
PkTicket int not null,
PkUser int not null, // add this
PkAttraction int not null, // add this
Portion int not null,
IdTransaction nvarchar(100) not null,
Payday datetime not null,
primary key(PkPayment, PkTicket),
// change to this
foreign key(PkTicket, PkUser, PkAttraction) references Ticket(PkTicket, PkUser, PkAttraction)
.....
)
When you not specify a name for FK and PK, SQL server generates a name. in this case, looks like SQL server generates duplicate name.
If you specify name for FK and PK, it will work.

Can one table have two identity columns in SQL Server?

I am trying to make two columns auto increment but this column shows an error [user_id] as id + 0 PRIMARY KEY NOT NULL saying
Only UNIQUE or PRIMARY KEY constraints can be created on computed columns
What I am trying to do is, if id = 1, make user_id= 1 as well.
CREATE TABLE [dbo.TBL_TXN_USER]
(
[id] int NOT NULL IDENTITY(1,1),
[user_id] as id + 0 PRIMARY KEY NOT NULL ,
[username] varchar(150) NOT NULL,
[fullname] varchar(150) NOT NUll,
[pwd] varchar(50) NOT NUll,
[email] varchar(150) NOT NULL,
[mobile] varchar(150) NOT NULL,
[designation] varchar(150) NOT NULL,
[deleted] int NULL,
[created_date] datetime NULL,
[creator_user_id] int NULL,
[changed_date] datetime NULL,
[changer_user_id] int NULL,
[add_content] int NULL,
[edit_content] int NULL,
[delete_content] int NULL,
[manage_user] int NULL,
[view_log] int NULL,
)
What is wrong in [user_id]? How to solve it?
the error message is because you put the NOT NULL constraint on the computed column.
on sql server 2012 the complete error message is:
Only UNIQUE or PRIMARY KEY constraints can be created on computed
columns, while CHECK, FOREIGN KEY, and NOT NULL constraints require
that computed columns be persisted.
here is a working script (i changed the table name):
CREATE TABLE dbo.[TBL_TXN_USER]
(
[id] int NOT NULL IDENTITY(1,1),
[user_id] as id + 0 persisted not null primary key,
[username] varchar(150) NOT NULL,
[fullname] varchar(150) NOT NUll,
[pwd] varchar(50) NOT NUll,
[email] varchar(150) NOT NULL,
[mobile] varchar(150) NOT NULL,
[designation] varchar(150) NOT NULL,
[deleted] int NULL,
[created_date] datetime NULL,
[creator_user_id] int NULL,
[changed_date] datetime NULL,
[changer_user_id] int NULL,
[add_content] int NULL,
[edit_content] int NULL,
[delete_content] int NULL,
[manage_user] int NULL,
[view_log] int NULL,
);
GO
i have a couple of comments about that question .
- a calculated field with a fixed formula with static values as primary key instead of the id itself is a waste of resources: one of the 2 fields should not be there
- a field with the name of a system function (user_id) is something i would avoid at all costs.
- the question looks like an attempt to put in place a solution (the calculated field as id) for an hidden issue.
Sorry for my misunderstanding, So you want to add auto increments two column in one table. Actually that is not accept at SQL-server so I am going to give you another option below
CREATE TRIGGER [dbo].[insert_triger] ON [dbo].[TBL_TXN_USER]
FOR INSERT
AS
update TBL_TXN_USER set [user_id] = id
where id = (
select MAX(id)
from TBL_TXN_USER
)
column aliases work with select statement not create table, also for [user_id] you didn't provide any data type.
Use the following to create your table :
CREATE TABLE [dbo.TBL_TXN_USER](
[id] int NOT NULL IDENTITY(1,1),
[user_id] int PRIMARY KEY NOT NULL ,
....rest of code
To update [user_id] consider using a trigger.

Retrieve data using select query with null Foreign key value

I have a 2 tables with name Vendor and VendorType . Structure are given
CREATE TABLE XCodesSCMERP.dbo.Vendor (
VendorID INT IDENTITY,
VendorTypeID INT NULL,
VendorName VARCHAR(200) NULL,
VendorCompany VARCHAR(200) NULL,
FirstName VARCHAR(100) NULL,
LastName VARCHAR(100) NULL,
Contact VARCHAR(100) NULL,
Phone VARCHAR(100) NULL,
AltContact VARCHAR(100) NULL,
Email VARCHAR(50) NULL,
AddressBilledFrom VARCHAR(50) NULL,
AddressShippedFrom VARCHAR(50) NULL,
VendorNotes VARCHAR(500) NULL,
OpeningBalance VARCHAR(100) NULL,
OpeningDate VARCHAR(100) NULL,
VendorAccountNo VARCHAR(100) NULL,
CONSTRAINT PK_Vendor PRIMARY KEY CLUSTERED (VendorID),
CONSTRAINT FK_Vendor_VendorTypeTable_VendorTypeID FOREIGN KEY (VendorTypeID) REFERENCES dbo.VendorTypeTable (VendorTypeID)
) ON [PRIMARY]
GO
CREATE TABLE XCodesSCMERP.dbo.VendorTypeTable (
VendorTypeID INT IDENTITY,
VendorType VARCHAR(100) NULL,
VendorDesc VARCHAR(MAX) NULL,
CONSTRAINT PK_VendorTypeTable PRIMARY KEY CLUSTERED (VendorTypeID)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
It is clear from structures of table that VendorTypeID is foreign key in Vendor table. Now when i want to retrieve data from Vendor table including field VendorType from VendorTypeTable than i have to use Inner Join that works fine.
But here is problem . it does' not show that records which don't have any vendorType i.e VendorTypeID is not selected . It is said to be null.
Now here is my question , how i can retrieve those records also that don't have any Vendor Type.
Would be pleasure for me , helping me in my Problem.
Note:
SELECT VendorID,VendorName,FirstName,LastName,VendorCompany,Contact,Phone,AltContact,Email,OpeningBalance,OpeningDate,VendorAccountNo ,VendorNotes FROM Vendor WHERE VendorTypeID='';
This query does not return any record.
If I understand correctly, you just want IS NULL:
SELECT v.*
FROM Vendor v
WHERE VendorTypeID IS NULL;
Modify your query to something like this
SELECT
VendorID,VendorName,FirstName,LastName,VendorCompany,Contact,Phone,AltContact,Email,OpeningBalance,OpeningDate,VendorAccountNo
,VendorNotes FROM Vendor WHERE VendorTypeID IS NULL;
Note: A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value is a blank field

Microsoft SQL, foreign key not referencing table, can't see what's causing it

I've spent a while trying to firgure it but but I can't see anything that would be causing this error. I'm thinking maybe something to do with the "Unique" statement.
Msg 1767, Level 16, State 0, Line 40
Foreign key 'FK_Loan_ItemNo__0AD2A005' references invalid table
'Item'.
Here's the code if someone wants to use it to replicate problem:
CREATE DATABASE LibrarySystem10
GO
USE LibrarySystem10
GO
CREATE TABLE MemberType(
MemberTypeNo int NOT NULL,
Name varchar(50) NOT NULL,
Description varchar(250) NOT NULL,
MaxNumberLoans int NOT NULL,
MaxLoanDuration int NOT NULL
PRIMARY KEY (MemberTypeNo)
)
insert into MemberType values ('0','UnderGraduate','A student at a college or university who has not yet earned a bachelor''s or equivalent degree.','5','10')
insert into MemberType values ('1','PostGraduate','A student undertaking study after completing a first degree.','10','10')
insert into MemberType values ('2','Staff','Staff at the university','15','15')
CREATE TABLE Member(
MemberNo int NOT NULL,
MemberTypeNo int NOT NULL,
FirstName varchar(150) NOT NULL,
LastName varchar(150) NULL,
DateOfBirth varchar (200) NULL,
HouseNo int NOT NULL,
Street varchar(50) NOT NULL,
Suburb varchar(100) NOT NULL,
PostCode int NOT NULL,
EmailAddress varchar(250) NULL,
HomePhoneNo varchar(250) NULL,
MobileNo varchar(250) NULL,
MembershipStartDate varchar (200) NOT NULL,
MembershipEndDate varchar (200) NOT NULL,
MembershipStatus varchar(100) NOT NULL,
PinNo int NOT NULL
PRIMARY KEY (MemberNo)
FOREIGN KEY (MemberTypeNo)REFERENCES MemberType ON UPDATE CASCADE
)
insert into member values ('0','0','Shane','Lindsay','15-11-1992','90','fake st','FauxTon','2250','shane#hotmai.com','0243296356','0415657164','15-11-2010','15-11-2020','current','0105')
insert into member values ('1','0','Shaune','Lincoln','18-12-1992','92','faken st','FauxTone','2350','shaune27#hotmai.com','0243253357','041565757','14-12-2010','14-12-2020','deferred','0123')
insert into member values ('2','0','Sarah','richards','08-08-1990','45','Small st','Hornsby','2279','Sarah67#hotmai.com','02432567154','0416451845','01-01-2012','01-01-2022','current','0123')
CREATE TABLE Loan(
MemberNo int NOT NULL FOREIGN KEY(MemberNo) REFERENCES Member ON UPDATE CASCADE,
ItemNo int NOT NULL FOREIGN KEY(ItemNo) REFERENCES Item ON UPDATE CASCADE,
DateLoaned varchar (50) NOT NULL,
DueDate varchar (50) NOT NULL,
Status varchar(50) NOT NULL,
FinesImposed bit NOT NULL DEFAULT '0' CHECK (finesImposed IN ('0','1')) ,
Renewed bit NOT NULL DEFAULT '0' CHECK (Renewed IN ('0','1')),
UNIQUE(MemberNo,ItemNo,DateLoaned)
)
insert into Loan values ('0','0','10-10-2012','15-10-2012','loaned','0','0')
insert into Loan values ('1','0','12-10-2012','15-10-2012','loaned','0','1')
CREATE TABLE Item(
ItemNo int NOT NULL,
Title varchar(50) NOT NULL,
Subject varchar(100) NULL,
ISBN int NULL,
PhysicalDescription varchar(150) NULL,
Author varchar(75) NULL,
PRIMARY KEY (ItemNo)
)
insert into Item values ('0','Book1','IT','0501425252','Big,42pages','John Doe')
insert into Item values ('1','Book2','IT','0501425253','Big,42pages','John Doe')
CREATE TABLE ItemCopy(
ItemNo int NOT NULL,
CallNumber varchar(50) NOT NULL,
Condition varchar(50) NULL,
UNIQUE(ItemNo,CallNumber),
PRIMARY KEY (CallNumber)
)
insert into ItemCopy values ('0','0','good')
CREATE TABLE Hold(
HoldNo int NOT NULL,
MemberNo int NOT NULL FOREIGN KEY(MemberNo) REFERENCES Member ON UPDATE CASCADE,
ItemNo int NOT NULL FOREIGN KEY(ItemNo) REFERENCES Item ON UPDATE CASCADE,
DateTimeHeld datetime NOT NULL,
comments varchar(200) NULL,
Status varchar(50) NOT NULL
PRIMARY KEY (HoldNo)
)
CREATE TABLE Fine(
FineNo int NOT NULL,
MemberNo int NOT NULL FOREIGN KEY(MemberNo) REFERENCES Member ON UPDATE CASCADE,
Description varchar(50) NULL,
Amount int NOT NULL,
PRIMARY KEY (FineNo)
)
CREATE TABLE AudioRecording(
Length varchar(50) NULL,
BitRate varchar(50) NULL,
Size varchar(50) NULL
)
CREATE TABLE ItemCollection(
ItemNo int NULL,
CollectionName varchar(75) NULL
UNIQUE (ItemNo,CollectionName)
)
CREATE TABLE Collection(
CollectionName varchar(75)NOT NULL
PRIMARY KEY (CollectionName)
)
CREATE TABLE Book(
PublisherInfo varchar(150) NULL,
Edition int NULL,
Notes varchar(250) NULL,
Status varchar(50) NULL
)
CREATE TABLE Journal(
Series int NULL,
Notes varchar(250) NULL,
OtherTitles varchar(150) NULL,
PriorTitles varchar(250) NULL
)
SELECT m.FirstName, l.Status, l.DueDate
FROM Member m, Loan l
WHERE m.MemberNo = '0' AND l.MemberNo = m.MemberNo
Loan references Item, but you create Loan before you create Item. Create the Item table first.