How to add check constraints in SQL Server? - tsql

I want to add the following constraint to the table named service in my database.
Constraint 1:
Neither DateCompleted nor DueDate can precede StartDate.
CREATE TABLE [Service] (
Service_ID INT NOT NULL PRIMARY KEY
, Invoice_ID INT
, Project_ID INT NOT NULL
, Description CHAR(20) NOT NULL
, Start_Date VARCHAR(10) NOT NULL
, Due_Date VARCHAR(10)
, Planned_Price VARCHAR(10)
, Actual_Price VARCHAR(10)
, Status CHAR(10) NOT NULL
, Date_Completed VARCHAR(10)
);
Another constraint should be added to the table named client.
Constraint 2:
Column Post_Code values should be positive integers with three or four digits.
CREATE TABLE [Client] (
Client_ID INT NOT NULL PRIMARY KEY
, First_Name VARCHAR(15) NOT NULL
, Last_Name VARCHAR(15) NOT NULL
, Street_Address VARCHAR(50)
, Suburb VARCHAR(15) NOT NULL
, State VARCHAR(3) NOT NULL
, Post_Code INT NOT NULL
, Phone_number INT NOT NULL
);

Service:
ALTER TABLE [Service]
ADD CONSTRAINT [service_datecheck]
CHECK ([StartDate] <= [DateCompleted] AND [StartDate] <= [DueDate]);
Client:
ALTER TABLE [Client]
ADD CONSTRAINT [client_postcodecheck]
CHECK ([Post_Code] > 0 AND LEN([Post_Code]) IN (3,4));

Related

postgresql display products that were ordered

i havŠµ tables like this and i need to display products that were ordered
create table customer (
id int primary key,
first_name varchar(100) not null,
last_name varchar(100) not null,
city varchar(100) null,
country varchar(100) null,
phone varchar(100) null
);
create table supplier (
id int primary key,
company_name varchar(100) not null,
contact_name varchar(100) null,
contact_title varchar(100) null,
city varchar(100) null,
country varchar(100) null,
phone varchar(100) null,
fax varchar(100) null
);
create table product (
id int primary key,
product_name varchar(100) not null,
unit_price decimal(12,2) null default 0,
package varchar(100) null,
is_discontinued boolean not null default false,
supplier_id int references supplier(id) not null
);
create table orders (
id int primary key,
order_date timestamp not null default now(),
order_number varchar(100) null,
total_amount decimal(12,2) null default 0,
customer_id int references customer(id) not null
);
create table order_item (
id int primary key,
unit_price decimal(12,2) not null default 0,
quantity int not null default 1,
order_id int references orders(id) not null,
product_id int references product(id) not null
);
If you only need product_name of products that were ordered, you can do the below sql. It involves only 2 tables.
select distinct p.product_name
from order_item o
join product p
on o.product_id = p.id
Postgres DB Fiddle

When using COPY FROM statement getting ERROR: null value in column "field_id" violates not-null constraint

I am using the COPY FROM command to load data from a file.
The table is defined with identity column, which is not part of the file.
CREATE TABLE APP2DBMAP (
FIELD_ID integer NOT NULL GENERATED BY DEFAULT AS IDENTITY,
FIELD_NAME varchar(128) ,
TABLE_NAME varchar(128) ,
COLUMN_NAME varchar(128) ,
CONSTRAINT PK_APP2DBMAP PRIMARY KEY ( FIELD_ID )
);
I executed the following COPY FROM command, the file contains 3 values in 1 row.
copy app2dbmap (field_name, table_name, column_name) from '/opt/NetMgr/data/templ_db.txt' DELIMITER ',' ;
And I got the following error:
ERROR: null value in column "field_id" violates not-null constraint
DETAIL: Failing row contains (null, 'aaa', 'bbb', 'ccc').
CONTEXT: COPY app2dbmap, line 1: "'aaa','bbb','ccc'"
I tried to change the column description of field_id to serial, and it did work fine.
I don't understand why it doesn't work with the original table definition.
The problem is you have specified the field_id to be a not null value and hence when the file is passing null as a value, your error is there.
If you want an auto increment id, Use,
CREATE TABLE APP2DBMAP (
FIELD_ID smallserial NOT NULL,
FIELD_NAME varchar(128) ,
TABLE_NAME varchar(128) ,
COLUMN_NAME varchar(128) ,
CONSTRAINT PK_APP2DBMAP PRIMARY KEY ( FIELD_ID )
);
You can also use bigserial(int4) instead of smallint(int8)
or you can give a default value,
CREATE TABLE APP2DBMAP (
FIELD_ID integer NOT NULL default 0,
FIELD_NAME varchar(128) ,
TABLE_NAME varchar(128) ,
COLUMN_NAME varchar(128) ,
CONSTRAINT PK_APP2DBMAP PRIMARY KEY ( FIELD_ID )
);
You will have to pass something, you cannot pass null in a not null column

NetBeans Generated REST Service works for XML requests, but not JSON

I am using NetBeans to help me build a REST web service. My steps taken have been the following:
New Project -> Web Application
New File -> Web Service -> RESTFul WebService from Database
Select the Datasource (which is a MySQL DB)
Everything generates, right click on project -> Test RESTFul
WebServices
When I want to test GET(application/XML), I can get a result returned fine, I can also get an XML response from a Jersey Client I made after the fact. But when I test the JSON functions, I always seem to get errors:
exception
javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper
root cause
org.glassfish.jersey.server.ContainerException:
java.lang.NoClassDefFoundError: Could not initialize class
org.eclipse.persistence.jaxb.BeanValidationHelper
root cause
java.lang.NoClassDefFoundError: Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper
My Database schema, which would really be the only thing I've written myself, is the following:
-- ****************** SqlDBM: MySQL ******************;
-- ***************************************************;
DROP TABLE `roles`;
DROP TABLE `orders`;
DROP TABLE `inventory`;
DROP TABLE `users`;
DROP TABLE `warehouses`;
DROP TABLE `inventory`;
DROP TABLE `addresses`;
DROP TABLE `products`;
-- ************************************** `addresses`
CREATE TABLE `addresses`
(
`addressID` INTEGER NOT NULL AUTO_INCREMENT ,
`streetNum` INTEGER NOT NULL ,
`streetName` VARCHAR(45) NOT NULL ,
`unitNum` INTEGER ,
`city` VARCHAR(45) NOT NULL ,
`province` VARCHAR(45) NOT NULL ,
`postalCode` VARCHAR(6) NOT NULL ,
PRIMARY KEY (`addressID`)
);
-- ************************************** `products`
CREATE TABLE `products`
(
`productID` INTEGER NOT NULL AUTO_INCREMENT ,
`productNO` VARCHAR(40) NOT NULL ,
`productName` VARCHAR(80) NOT NULL ,
`productDesc` VARCHAR(160) NOT NULL ,
`cost` REAL NOT NULL ,
`price` REAL NOT NULL ,
PRIMARY KEY (`productID`)
);
-- ************************************** `users`
CREATE TABLE `users`
(
`userID` INTEGER NOT NULL AUTO_INCREMENT ,
`firstName` VARCHAR(20) NOT NULL ,
`lastName` VARCHAR(20) NOT NULL ,
`dateOfBirth` DATE NOT NULL ,
`email` VARCHAR(45) NOT NULL ,
`password` CHAR(64) NOT NULL ,
`addressID` INTEGER NOT NULL ,
PRIMARY KEY (`userID`),
KEY `fkIdx_87` (`addressID`),
CONSTRAINT `FK_87` FOREIGN KEY `fkIdx_87` (`addressID`) REFERENCES `addresses` (`addressID`)
);
-- ************************************** `warehouses`
CREATE TABLE `warehouses`
(
`warehouseID` INTEGER NOT NULL AUTO_INCREMENT ,
`addressID` INTEGER NOT NULL ,
PRIMARY KEY (`warehouseID`),
KEY `fkIdx_58` (`addressID`),
CONSTRAINT `FK_58` FOREIGN KEY `fkIdx_58` (`addressID`) REFERENCES `addresses` (`addressID`)
);
-- ************************************** `inventory`
CREATE TABLE `inventory`
(
`id` INTEGER NOT NULL AUTO_INCREMENT ,
`productID` INTEGER NOT NULL ,
`warehouseID` INTEGER NOT NULL ,
`expiry` DATE NOT NULL ,
`productID_1` INTEGER NOT NULL ,
PRIMARY KEY (`id`),
KEY `fkIdx_31` (`productID_1`),
CONSTRAINT `FK_31` FOREIGN KEY `fkIdx_31` (`productID_1`) REFERENCES `products` (`productID`)
);
-- ************************************** `roles`
CREATE TABLE `roles`
(
`roleID` INTEGER NOT NULL AUTO_INCREMENT ,
`roleName` VARCHAR(20) NOT NULL ,
`userID` INTEGER NOT NULL ,
PRIMARY KEY (`roleID`),
KEY `fkIdx_96` (`userID`),
CONSTRAINT `FK_96` FOREIGN KEY `fkIdx_96` (`userID`) REFERENCES `users` (`userID`)
);
-- ************************************** `orders`
CREATE TABLE `orders`
(
`orderID` INTEGER NOT NULL AUTO_INCREMENT ,
`orderNum` INTEGER NOT NULL ,
`productID` INTEGER NOT NULL ,
`quantity` INTEGER NOT NULL ,
`userID` INTEGER NOT NULL ,
PRIMARY KEY (`orderID`),
KEY `fkIdx_70` (`productID`),
CONSTRAINT `FK_70` FOREIGN KEY `fkIdx_70` (`productID`) REFERENCES `products` (`productID`),
KEY `fkIdx_100` (`userID`),
CONSTRAINT `FK_100` FOREIGN KEY `fkIdx_100` (`userID`) REFERENCES `users` (`userID`)
);
-- ************************************** `inventory`
CREATE TABLE `inventory`
(
`id` INTEGER NOT NULL AUTO_INCREMENT ,
`expiry` DATE ,
`productID` INTEGER NOT NULL ,
`warehouseID` INTEGER NOT NULL ,
PRIMARY KEY (`id`),
KEY `fkIdx_40` (`productID`),
CONSTRAINT `FK_40` FOREIGN KEY `fkIdx_40` (`productID`) REFERENCES `products` (`productID`),
KEY `fkIdx_62` (`warehouseID`),
CONSTRAINT `FK_62` FOREIGN KEY `fkIdx_62` (`warehouseID`) REFERENCES `warehouses` (`warehouseID`)
);

Constraints on dates

I need Help with implementing a database in SQL Developer. I tried to implement date constraints but it doesn't work the way I want to.
Here is Office Table:
CREATE TABLE Office (
Office_ID varchar2(7) PRIMARY KEY NOT NULL,
Office_AddressLine varchar2(50) NOT NULL,
Office_PostCode varchar2(8) NOT NULL,
Office_Telephone varchar2(11),
Office_Email varchar2(30), PRIMARY KEY(Office_ID),
CONSTRAINT Office_Email_CK CHECK ( Office_Email like '%_#__%._%')
);
Here is Employee Table:
CREATE TABLE Employee (
Employee_ID varchar2(10) PRIMARY KEY NOT NULL,
Office_ID varchar2(7) NOT NULL,
Emp_FirstName varchar2(20) NOT NULL,
Emp_LastName varchar2(20) NOT NULL,
Emp_Gender varchar2(1) NOT NULL,
Emp_DateOfBirth Date NOT NULL,
Hire_Date date NOT NULL,
Emp_Telephone varchar2(11),
Emp_Email varchar2(30),
Emp_AddressLine varchar2(50) NOT NULL,
Emp_PostCode varchar2(8) NOT NULL,
Emp_Speciality varchar2(20) NOT NULL,
Emp_Qualification varchar2(20) NOT NULL,
Emp_AwardingBody varchar2(30) NOT NULL,
Emp_Salary number(6) NOT NULL,
Employment_History1 varchar2(50),
Employment_History2 varchar2(50),
Employment_History3 varchar2(50) ,
CONSTRAINT fk_staff_office FOREIGN KEY (Office_ID) REFERENCES office (Office_ID),
CONSTRAINT Emp_DateOfBirth_CK CHECK (Emp_DateOfBirth BETWEEN Date '1900-01-01' AND Date '2018-01-01'),
CONSTRAINT Emp_Gender_CK CHECK (Emp_Gender in ('M','F')),
CONSTRAINT Emp_Email_CK CHECK ( Emp_Email like '%_#__%._%')
);
It works this way, but what I want is this:
CREATE TABLE Employee (
Employee_ID varchar2(10) NOT NULL,
Office_ID varchar2(7) NOT NULL,
Emp_FirstName varchar2(20) NOT NULL,
Emp_LastName varchar2(20) NOT NULL,
Emp_Gender varchar2(1) NOT NULL, Emp_DateOfBirth Date NOT NULL,
Hire_Date date NOT NULL,
Emp_Telephone varchar2(11),
Emp_Email varchar2(30),
Emp_AddressLine varchar2(50) NOT NULL,
Emp_PostCode varchar2(8) NOT NULL,
Emp_Speciality varchar2(20) NOT NULL,
Emp_Qualification varchar2(20) NOT NULL,
Emp_AwardingBody varchar2(30) NOT NULL,
Emp_Salary number(6) NOT NULL,
Employment_History1 varchar2(50),
Employment_History2 varchar2(50),
Employment_History3 varchar2(50) ,
PRIMARY KEY (Employee_ID),
CONSTRAINT fk_staff_office FOREIGN KEY (Office_ID) REFERENCES office (Office_ID)
CONSTRAINT fk_staff_patient FOREIGN KEY (Patient_ID) REFERENCES Patient (Patient_ID),
CONSTRAINT Emp_DateOfBirth_CK CHECK (Emp_DateOfBirth BETWEEN Date '1900-01-01' AND Date sysdate),
CONSTRAINT Hire_Date_CK CHECK (Hire_Date <= curdate()),
CONSTRAINT Emp_Gender_CK CHECK (Emp_Gender in ('M','F')),
CONSTRAINT Emp_Email_CK CHECK ( Emp_Email like '%_#__%._%')
);
I don't know why sysdate function or getdate doesn't work and I also don't know how to implement the Constraint about the Hire_Date (I cannot do it with <= relationship). As it is now I have to give up in implementing them even if I will lose points.
Any help will be much appreciated.
You'll need a trigger to enforce such a constraint. Here's an example:
SQL> create table test
2 (
3 employee_id varchar2 (10),
4 hire_date date
5 );
Table created.
SQL> create or replace trigger trg_hd_biu
2 before insert or update of hire_date
3 on test
4 for each row
5 begin
6 if :new.hire_date not between date '1900-01-01' and sysdate
7 then
8 raise_application_error (-20001, 'Hire date out of range');
9 end if;
10 end;
11 /
Trigger created.
SQL> insert into test values ('1', date '2018-01-15');
1 row created.
SQL> insert into test values ('2', date '2018-05-25');
insert into test values ('2', date '2018-05-25')
*
ERROR at line 1:
ORA-20001: Hire date out of range
ORA-06512: at "SCOTT.TRG_HD_BIU", line 4
ORA-04088: error during execution of trigger 'SCOTT.TRG_HD_BIU'
SQL>
I have done it already using another approach (because our teacher doesn't want us to create triggers. We have to make use of constraints only) and it works. Thanks for help any way.
CREATE TABLE Employee (
Employee_ID varchar2(10) PRIMARY KEY NOT NULL,
Office_ID varchar2(7) NOT NULL,
Emp_FirstName varchar2(20) NOT NULL,
Emp_LastName varchar2(20) NOT NULL,
Emp_Gender varchar2(1) NOT NULL,
Emp_DateOfBirth Date NOT NULL,
Hire_Date date NOT NULL,
Emp_CurrentDate date default sysdate,
Emp_Telephone varchar2(11) NOT NULL,
Emp_Email varchar2(30) NOT NULL,
Emp_AddressLine varchar2(50) NOT NULL,
Emp_PostCode varchar2(8) NOT NULL,
Emp_Speciality varchar2(20) NOT NULL,
Emp_Qualification varchar2(20) NOT NULL,
Emp_AwardingBody varchar2(30) NOT NULL,
Emp_Salary number(6) NOT NULL,
Emp_Supervised_By varchar2(10) NOT NULL,
Employment_History1 varchar2(50),
Employment_History2 varchar2(50),
Employment_History3 varchar2(50) ,
CONSTRAINT fk_staff_office FOREIGN KEY (Office_ID) REFERENCES office (Office_ID),
CONSTRAINT Hire_Date_CK check (Hire_Date < Emp_CurrentDate AND (Hire_Date - Emp_DateOfBirth)/365 > 18),
CONSTRAINT Emp_DateOfBirth_CK check (Emp_DateOfBirth > TO_DATE('1900-01-01', 'YYYY-MM-DD')),
CONSTRAINT Emp_Salary_CK check (Emp_Salary > 0 AND Emp_Salary < 150000),
CONSTRAINT Emp_Gender_CK CHECK (Emp_Gender in ('M','F')),
CONSTRAINT Emp_Email_CK CHECK ( Emp_Email like '%_#__%._%'),
CONSTRAINT Emp_Telephone_CK CHECK (regexp_like(Emp_Telephone, '^[0123456789]{11}$') AND Emp_Telephone like '0%'),
CONSTRAINT Emp_FirstName_CK CHECK (regexp_like(Emp_FirstName, '^[ABCDEFGHIJKLMNOPQRSTUVWXYZ]{1,20}$')),
CONSTRAINT Emp_LastName_CK CHECK (regexp_like(Emp_LastName, '^[ABCDEFGHIJKLMNOPQRSTUVWXYZ]{1,20}$')),
CONSTRAINT Emp_PostCode_CK CHECK (regexp_like ( Emp_PostCode , '([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\s?[0-9][A-Za-z]{2})')),
CONSTRAINT Emp_Speciality_CK CHECK (regexp_like(Emp_Speciality, '^[ABCDEFGHIJKLMNOPQRSTUVWXYZ ]{1,20}$')),
CONSTRAINT Emp_Qualification_CK CHECK (regexp_like(Emp_Qualification, '^[ABCDEFGHIJKLMNOPQRSTUVWXYZ ]{1,20}$')),
CONSTRAINT Emp_AwardingBody_CK CHECK (regexp_like(Emp_AwardingBody, '^[ABCDEFGHIJKLMNOPQRSTUVWXYZ ]{1,30}$'))
);
What I want to do now is to create a constraint that enables me to set the value of the attribute Emp_Supervised_By automatically as the same value of the Employee_ID attribute when the Emp_Speciality is 'Manager'. Thanks in advance for help!

postgresql cannot insert data to newly added column

In postgresql I have a table which I need to add a new column. the original table ddl is belowing:
CREATE TABLE survey.survey_response (
id uuid NOT NULL DEFAULT uuid_generate_v4(),
survey_id uuid NOT NULL,
survey_question_id uuid NULL,
user_id varchar(256) NULL,
device_id varchar(256) NULL,
user_country varchar(100) NULL,
client_type varchar(100) NULL,
product_version varchar(100) NULL,
answer text NULL,
response_date timestamptz NOT NULL DEFAULT now(),
survey_category varchar(100) NULL,
tags varchar(250) NULL,
tracking_id uuid NULL,
CONSTRAINT survey_response_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
) ;
Then I alter the table to add a new column:
alter table survey.survey_response add column system_tags varchar(30) ;
But after that I found my instert statement cannot make change to this new column, for all the original columns it works fine:
INSERT INTO survey.survey_response
(id, survey_id, user_id, tags, system_tags)
VALUES(uuid_generate_v4(), uuid_generate_v4(),'1123','dsfsd', 'dsfsd');
select * from survey.survey_response where user_id = '1123';
The "tags" columns contains inserted value, however, system_tags keeps null.
I tested the above scenario in my local postgreSQL 9.6, any ideas about this strange behavior? Thanks a lot
-----------------update----------
I found this survey.survey_response table has been partitioning based on month, So my inserted record will also be displayed in survey.survey_response_y2017m12. but the new system_tags column is also NULL
CREATE TABLE survey.survey_response_y2017m12 (
id uuid NOT NULL DEFAULT uuid_generate_v4(),
survey_id uuid NOT NULL,
survey_question_id uuid NULL,
user_id varchar(256) NULL,
device_id varchar(256) NULL,
user_country varchar(100) NULL,
client_type varchar(100) NULL,
product_version varchar(100) NULL,
answer text NULL,
response_date timestamptz NOT NULL DEFAULT now(),
survey_category varchar(100) NULL,
tags varchar(250) NULL,
tracking_id uuid NULL,
system_tags varchar(30) NULL,
CONSTRAINT survey_response_y2017m12_response_date_check CHECK (((response_date >= '2017-12-01'::date) AND (response_date < '2018-01-01'::date)))
)
INHERITS (survey.survey_response)
WITH (
OIDS=FALSE
) ;
If I run the same scenario in a non-partition table then the insert works fine.
So do I need any special settings for alter table for partition table?
Old thread but you need to drop and create again the RULE to fix the issue.