Can someone help? Im trying to create then modify a table. INSERT statement conflicted with the CHECK constraint "chk_Sex" - sql

I am attempting to create a table then add and modify it. Below is how I created the table. The other part is the first record I attempted to add to the the table that has given me the check constrain Error
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the CHECK constraint "chk_Sex". The conflict occurred in database "MHaynes_F22", table "dbo.DogLicense", column 'Sex'.
The statement has been terminated.
CREATE TABLE DogLicense
(
License int identity (1,1) primary key Not Null,
Expires date,
Sex nvarchar(15),
PetName nvarchar(20),
Breed nvarchar(20),
OwnerLastName nvarchar(30),
OwnerFirstName nvarchar(30),
Address nvarchar(50),
Zip nvarchar(5),
Phone nvarchar(10),
CONSTRAINT chk_Sex CHECK (Sex IN ('M(Male)', 'F(Female)','NM(Neutered Male)','SF(Spayed Female)')),
CONSTRAINT chk_Expires CHECK(Expires > '01/01/1990'))
this is the first records I attempted to insert
insert DogLicense values('06/21/2023','NM','Rosco','St.Bernard','Freeman','Mark','123 Meadow Ln.','99207','(509) 555-1212')

Check constraints are strict. Because you asked it to accept only 'NM(Neutered Male)' (and others but not 'NM') you can only use that value:
insert DogLicense
values('06/21/2023','NM(Neutered Male)','Rosco','St.Bernard','Freeman','Mark','123 Meadow Ln.','99207','(509) 555-1212')

Related

The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Messages__Email__3D9E16F4"

Maybe someone can tell me why this is happening. I wrote this stored procedure:
CREATE PROCEDURE Newmessages
#Message_id VARCHAR(20)
,#First_name VARCHAR(20)
,#Last_name VARCHAR(20)
,#Email VARCHAR(20)
,#Phone VARCHAR(20)
,#Postal_code VARCHAR(20)
,#Notification_1 BIT
,#Notification_2 BIT
,#Own_Pets BIT
,#Organization_Id VARCHAR(20)
,#Animal_Id VARCHAR(20)
AS
INSERT INTO [dbo].[Messages]
VALUES (#Message_id, #First_name, #Last_name, #Email, #Phone,
#Postal_code, #Notification_1, #Notification_2, #Own_Pets,
#Organization_Id, #Animal_Id)
Now I'm trying to check it by inserting:
exec Newmessages '64654', 'Kelli', 'Adkins', 'acprthvs.bpuzcnt#gmail.com', '478-6273327', 'SR5 2QF', 'False', 'False', 'False', '91839', '40550'
and I get:
Msg 547, Level 16, State 0, Procedure Newmessages, Line 4 [Batch Start Line 0] > The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Messages__Email__3D9E16F4". The conflict occurred in database "Petfinder", table "dbo.Users", column 'Email'.
Thing is, I checked and I do have the email I'm trying to insert in the Users table (which is the error).
Here I checked that it does exist in dbo.Users:
Does anyone know why this is still happening?
The email address you're trying to insert is acprthvs.bpuzcnt#gma, which doesn't exist in your table.
CREATE PROCEDURE Newmessages
...
,#Email VARCHAR(20)
...
The email address you'd like to enter is 26 characters long.
Use an explicit column list on the INSERT to map the columns explicitly:
INSERT INTO [dbo].[Messages] (Message_ID,First_Name, Last_name, Email, Phone, ...)
VALUES (
#Message_id
,#First_name
,#Last_name
,#Email
,#Phone
,#Postal_code
,#Notification_1
,#Notification_2
,#Own_Pets
,#Organization_Id
,#Animal_Id
)

Msg 547, The INSERT statement conflicted with the FOREIGN KEY constraint

In SQL Server 2012 Management studio, I tried many time to create some tables and insert into the tables some values, but the problem here is in relationship with tables :
The INSERT statement conflicted with the FOREIGN KEY constraint
The Errors :
Msg 8152, Level 16, State 14, Line 116 String or binary data would be
truncated.
Msg 547, Level 16, State 0, Line 122 The INSERT statement conflicted
with the FOREIGN KEY constraint "eworkerFK". The conflict occurred in
database "7", table "dbo.member_clup", column 'manager_id'.
The statement has been terminated.
Msg 547, Level 16, State 0, Line 128
The INSERT statement conflicted with the FOREIGN KEY constraint
"SALEDFk". The conflict occurred in database "7", table "dbo.worker",
column 'worker_number'.
Can anyone help me to insert values into the correct
tables ?
CREATE TABLE address
(
code_place int,
PLACE_NAME VARCHAR (15),
OUT_israel varchar (15)
CONSTRAINT address1 PRIMARY KEY(code_place)
)
create table member_clup
(
manager_id int,
manager_name varchar(15),
manager_last varchar(12),
phone_num int,
type varchar(10),
CONSTRAINT manager1PK PRIMARY KEY(manager_id)
)
create table worker
(
worker_number int,
worker_name varchar(50),
worker_last varchar(49),
id varchar(9),
type varchar(50),
manager_id int
CONSTRAINT workerPK PRIMARY KEY(worker_number)
CONSTRAINT eworkerFK FOREIGN KEY(manager_id)
REFERENCES member_clup(manager_id)
)
CREATE TABLE rooms(
room_number int,
floor int,
room_type varchar(8)
CONSTRAINT roomsKEY PRIMARY KEY(room_number)
)
CREATE TABLE cars
(
cars_number int,
car_type varchar(15),
car_model int,
CONSTRAINT carsPK PRIMARY KEY(cars_number)
)
CREATE TABLE tourest(
Cust_number int ,
Cust_name varchar(50),
cust_lastname varchar(50),
cust_phone varchar(10),
code_place int,
Room_id int,
Saledby int
CONSTRAINT tourest1 PRIMARY KEY(Cust_number)
CONSTRAINT addressFK FOREIGN KEY(code_place)
REFERENCES address(code_place),
CONSTRAINT SALEDFk FOREIGN KEY(Saledby)
REFERENCES worker(worker_number),
CONSTRAINT roomsFK FOREIGN KEY(Room_id)
REFERENCES rooms(room_number)
)
CREATE TABLE kesher
(
Cust_number int,
cars_number int,
CONSTRAINT custPK1 PRIMARY KEY(Cust_number,cars_number),
CONSTRAINT kesher1FK FOREIGN KEY(Cust_number)
REFERENCES cars(cars_number),
CONSTRAINT kesherFK FOREIGN KEY(Cust_number)
REFERENCES tourest(Cust_number)
)
insert into cars VALUES
(100100,'mazda',2002),
(100205,'ford',2017),
(100206,'porch',1998),
(100207,'mazda',2017),
(100208,'opel',2002),
(100209,'mazda',2016),
(100210,'pijuot',2002),
(100211,'mazda',2015),
(100212,'mazda',2010),
(100213,'volvo',2002),
(100215,'ford',20012)
insert into rooms VALUES
(100,1,'single'),
(101,1,'double'),
(102,1,'single'),
(103,1,'double'),
(201,2,'signle'),
(202,2,'signle'),
(203,2,'signle'),
(204,2,'signle'),
(300,3,'double'),
(301,3,'double'),
(302,3,'double'),
(303,3,'double'),
(304,3,'signle')
insert into address VALUES
(500,'Akko','no'),
(501,'Haifa','no'),
(502,'Nahariya','no'),
(503,'Nataniya','no'),
(504,'carmieal','no'),
(505,'Nahef','no'),
(507,'Nitsrat','no'),
(510,'OUT','yes')
insert into member_clup VALUES
(5400,'shmolek','snaa','0525732572','General'),
(5696,'malloc','ali','0525552501','Rooms'),
(5991,'ramada','hassan','0532731212','Rooms & Tips'),
(5210,'meri','yako','0525022572','General Manager')
insert into worker
VALUES(1234,'halaa','khaled',1234567,'none',5696),
(2234,'fares','adoon',6542897,'none',5696),
(6670,'halaa','khaled',1001234,'none',5991),
(2554,'halaa','khaled',5658741,'none',5210),
(9987,'halaa','khaled',1123456,'none',5400)
insert into tourest VALUES
(1510,'moshe','yke','0525732579',500,101,2234),
(1520,'ninar','lait','052655541',500,102,6670),
(1521,'hasan','ahmad','0532578741',501,101,2234),
(1522,'ameer','karm','0545222741',500,104,6670),
(1523,'aliel','sraa','0525771572',504,100,2234),
(1524,'hasa','veto','0525122579',505,303,6670),
(1525,'saed','snaa','05255632579',505,303,2234),
(1526,'yakov','mero','0528132579',502,202,6670),
(1527,'mece','loka','0525962579',502,302,9987),
(1528,'ana','yokaf','0525791179',502,302,9987),
(1529,'lelya','mandlina','0527832579',505,203,9987),
(1530,'mnal','khokha','0525758579',507,204,5991),
(1531,'moka','panana','0525805579',507,200,2234)
insert into kesher VALUES
(1510,100100),
(1520,100209),
(1521,100100),
(1522,100209),
(1523,100206),
(1524,100206),
(1525,100213),
(1526,100206),
(1527,100213),
(1528,100213),
(1529,100209)
This code is straightforward to debug, you surely can work it out. Run each statement on it's own and see its result. If it fails, split it into smaller statements and repeat. If you can't split it, it's already small enough to debug by eyesight, it won't take long to figure the issue.
Before debugging though, know this, restarting from scratch is sometimes helpful/necessary, so have restart script(s) ready. In this scenario only a bunch of DROP TABLEs are necessary, they'll remove the tables and their records.
Your CREATE TABLE statements are working fine, that's one thing passed. Even if you had problems with them though, run them one by one to debug, not all at once.
Your INSERTs are problematic, yeah. Run each INSERT block one by one, and for the block that fails, split it into individual INSERT statements, one per record, and now you'll be able to tell which row is the problem.
Even though you cite certain foreign key conflict issues, I'm getting a bunch of different foreign key issues. Double-check the code you provided. Also,
the order of what statement is ran first matters (can I furnish the third floor of my house while I don't even have third and second floors? Can you cancel a booking that you didn't book yet?)
Lastly, the data seem to have truncation issues, whether the table column should be bigger or the records' values are incorrect is something only you can tell.

SQL Trigger Store Procedure Compile Error

I have a question on what is giving me this error:
Msg 547, Level 16, State 0, Procedure AddIntoClass, Line 12
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_CourseEnrolled_StudentDemographic". The conflict occurred in database "PK_Final", table "dbo.StudentDemographic", column 'StudentID'.
This is my code so far:
Create Procedure AddIntoClass(#StudentID int, #CourseName nvarchar(30),
#SectionNumber nvarchar(30), #TimeOfDay nvarchar(30), #Term int)
As
Begin
Insert into CourseEnrolled
Values(#StudentID, #CourseName, #SectionNumber, #TimeOfDay, #Term)
End
EXEC AddIntoClass 2, 'Biology', '1003', '2:00pm', 2
Any help would be appriciated, Thanks!
Before inserting into CourseEnrolled table, the student id value of "2", should be available in the StudentDemographic table.
You are inserting StudentId value of "2" into CourseEnrolled table, which has a foreign key reference on "StudentId" to StudentDemographic table.

Insert fails due to "column not allowed here" error

I am a beginner with SQL. I have created 4 tables and added data to my SHIP table. I am having some issues with inserting data into the CRUISE table. I get the error message at the bottom.
I have researched and can not figure out what i am doing wrong. Is there an issue with my sequence and/or trigger that is not allowing me to do this or is my syntax in the CREATE TABLE CRUISE causing the error? Everything i have done has been successful up until trying to insert the first column into the CRUISE table.
The tables:
CREATE TABLE SHIP
( Ship_Name VARCHAR2(100) PRIMARY KEY,
Ship_Size INTEGER,
Ship_Registry VARCHAR2(50),
Ship_ServEntryDate INTEGER,
Ship_PassCapacity INTEGER,
Ship_CrewCapacity INTEGER,
Ship_Lifestyle VARCHAR2(40),
CONSTRAINT Size_ck CHECK (Ship_Size > 0),
CONSTRAINT Registry_ck CHECK (Ship_Registry IN ('Norway','Liberia','The Netherlands','Bahamas'))
)
CREATE TABLE CRUISE (
Cruise_ID INTEGER Primary Key,
Ship_Name VARCHAR(100),
Cruise_DeptDate DATE NOT NULL,
Cruise_DeptCity VARCHAR(80) NOT NULL,
Cruise_Duration INTEGER,
FOREIGN KEY (Ship_Name) REFERENCES SHIP(Ship_Name)
)
CREATE TABLE PASSENGERS (
Pass_ID INTEGER PRIMARY KEY,
Pass_Name VARCHAR(100) NOT NULL,
Pass_City VARCHAR(80),
Pass_Telephone VARCHAR(15),
Pass_NextOfKin VARCHAR(100)
)
CREATE TABLE RESERVATIONS (
Pass_ID INTEGER NOT NULL,
Cruise_ID INTEGER NOT NULL,
Res_TotalCost NUMERIC(9,2),
Res_BalanceDue NUMERIC(9,2),
Res_SpecialRequest VARCHAR(30),
Res_Room VARCHAR(10),
FOREIGN KEY (Pass_ID) REFERENCES PASSENGERS(Pass_ID),
FOREIGN KEY (Cruise_ID) REFERENCES CRUISE(Cruise_ID),
CONSTRAINT Cost_ck CHECK (Res_TotalCost >= 0),
CONSTRAINT BalanceDue_ck CHECK (Res_BalanceDue >= 0),
CONSTRAINT SpecialRequest_ck CHECK (Res_SpecialRequest IN ('Vegetarian','Vegan','Low salt','Gluten free','Kosher','Other'))
)
The sequence/trigger is an attempt to auto number Cruise_ID.
Create SEQUENCE cruise_id_sq
START WITH 1
INCREMENT BY 1;
CREATE OR REPLACE TRIGGER cruise_id_t
BEFORE INSERT
ON CRUISE
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
if(:new.Cruise_ID is null) then
SELECT cruise_id_sq.nextval
INTO :new.Cruise_ID
FROM dual;
end if;
END;
ALTER TRIGGER cruise_id_t ENABLE;
Inserting into SHIP is okay....
INSERT INTO SHIP
(Ship_Name, Ship_Size, Ship_Registry,Ship_ServEntryDate, Ship_PassCapacity,Ship_CrewCapacity,Ship_Lifestyle)
Values ('Carribean Princess',142000,'Liberia',1000,3100,1181,'Contemporary');
INSERT INTO SHIP
(Ship_Name, Ship_Size, Ship_Registry,Ship_ServEntryDate, Ship_PassCapacity,Ship_CrewCapacity,Ship_Lifestyle)
Values ('Carribean Sunshine',74000,'Norway',1992,1950,760,'Premium');
INSERT INTO SHIP
(Ship_Name, Ship_Size, Ship_Registry,Ship_ServEntryDate, Ship_PassCapacity,Ship_CrewCapacity,Ship_Lifestyle)
Values ('Ship of Dreams',70000,'Liberia',2004,1804,735,'Contemporary');
INSERT INTO SHIP
(Ship_Name, Ship_Size, Ship_Registry,Ship_ServEntryDate, Ship_PassCapacity,Ship_CrewCapacity,Ship_Lifestyle)
Values ('Sunshine of the Seas',74000,'The Netherlands',1990,2354,822,'Luxury');
Inserting into CRUISE fails...
INSERT INTO Cruise
(Ship_Name, Cruise_DeptDate,Cruise_DeptCity,CruiseDuration)
Values ('Sunshine of the Seas',25-may-15,'Miami',10);
Error starting at line : 1 in command - INSERT INTO Cruise (Ship_Name,
Cruise_DeptDate,Cruise_DeptCity,CruiseDuration) Values ('Sunshine of
the Seas',25-may-15,'Miami',10) Error at Command Line : 3 Column : 35
Error report - SQL Error: ORA-00984: column not allowed here
00984. 00000 - "column not allowed here"
*Cause:
*Action:
Oracle thinks that 25-may-15 is the expression 25 minus may minus 15. In looking up the value for may Oracle finds that there is nothing there. Thus the error.
You can, but probably don't want to, quote it like so, '25-may-15'. This will make a string that may or may not be implicitly converted to a date, depending on the settings of NLS_DATE_FORMAT and or NLS_TERRITORY.
To form a date independent of session setting one can use the TO_DATE function with explicit date format, to_date('25-may-15', 'DD-Mon-YY'). Another option is a date literal, date '2015-05-25', which is always YYYY-MM-DD no matter the session settings..

Self reference to the table

I'm new to SQL Server.
I want to reference the same table column as below,
CREATE TABLE JOIN_DEPARTMENTS
(
DEPTID INT PRIMARY KEY,
DEPTNAME VARCHAR(20)
);
CREATE TABLE JOIN_EMPLOYEES
(
EMPID INT PRIMARY KEY,
EMPNAME VARCHAR(20),
MGRID INT,
DEPTID INT FOREIGN KEY REFERENCES JOIN_DEPARTMENTS(DEPTID),
CONSTRAINT FK_SELFREFE FOREIGN KEY (MGRID) REFERENCES EMPLOYEES(EMPID) ON DELETE SET NULL
);
INSERT INTO JOIN_DEPARTMENTS VALUES (100, 'BFS');
INSERT INTO JOIN_DEPARTMENTS VALUES (101, 'MELT');
INSERT INTO JOIN_EMPLOYEES VALUES(1, 'SARA', NULL, 100); --> inserts fine
INSERT INTO JOIN_EMPLOYEES VALUES(2, 'SANTHOSH', 1, 100); -->
Throws the following error
Msg 547, Level 16, State 0, Line 530
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_SELFREFE". The conflict occurred in database "SARA", table "dbo.EMPLOYEES", column 'EMPID'.
What I am doing wrong, here?
Your constraint references EMPLOYEES but you are inserting into JOIN_EMPLOYEES - check EMPLOYEES to make sure an EMPID=1 exists, or modify your constraint to check JOIN_EMPLOYEES instead of EMPLOYEES
EDIT: In response to comment: I don't know how to make the self referencing ON DELETE SET NULL constraint work, but I think you could accomplish the same goal by creating an AFTER DELETE trigger that set MGRID to NULL in all rows where MGRID = EMPID of the deleted row(s). I can't fully test this, but I think this will work
CREATE TRIGGER trJOIN_EMPLOYEE_AfterDel ON JOIN_EMPLOYEES AFTER DELETE
AS BEGIN
SET NOCOUNT ON;
UPDATE JOIN_EMPLOYEES SET MGRID = NULL
WHERE MGRID IN (SELECT EMPID FROM deleted)
END
Basically what it does is after your delete has been processed, but before the transaction is considered complete, it goes back and also sets to NULL any MGRIDs that referenced the recently dropped employee ID.
Note that Microsoft has some relevant info
http://technet.microsoft.com/en-us/library/ms186973%28v=sql.105%29.aspx
says "The series of cascading referential actions triggered by a single DELETE or UPDATE must form a tree that contains no circular references." so I don't think you're going to get the self referential constraint to work.
Also note that you might have to remove some or all of the constraints before it will let you create that trigger, I think it's just INSTEAD OF DELETE triggers that conflict, but there is a chance AFTER DELETE triggers might conflict with some constraints - again, not enough experience here for me to be certain, try it and see.