I am trying to get my PL/SQL code to run but I keep running into issues. I am trying to get my Canadian postal code to be valid and it keeps giving getting error SQL Error: ORA-02290: check constraint (ORCL2_21.CK_INVESTOR_POSTAL_CODE) violated and the province needs to be two chars and all caps only can be valid and it wont compile the test code i have.
Create table Investor
(
Investor_Number Number(7,0)
Constraint PK_Investor_Investor_Number Primary Key
Constraint NN_Investor_Investor_Number Not Null,
First_Name Varchar2(25)
Constraint NN_Investor_First_Name Not Null,
Last_Name Varchar2(30)
Constraint NN_Investor_Last_Name Not Null,
Street_Address Varchar2(35)
Constraint NL_Investor_Street_Address Null,
City Varchar2(25)
Constraint NL_Investor_City Null,
Province Char(2)
Constraint CK_Investor_Province Check (Province in ('__'))
Constraint CK_Investor_Province_Caps Check (Province = UPPER(province))
Constraint NL_Investor_Province Null,
Postal_Code Varchar2(7)
Constraint CK_Investor_Postal_Code Check (REGEXP_like(Postal_Code,'[A-Z][0-9][A-Z][0-9][A-Z][0-9]')) --Having problem getting postal code to work on test inserts code!!!!!!
Constraint NL_Investor_Postal_Code Null,
Area_Code Number(3,0)
Default '780'
Constraint NN_Investor_Area_Code Not Null,
Phone_Number Number(7,0)
Constraint NN_Investor_Phone_Number Not Null,
Email_Address Varchar2(50)
Constraint CK_Investor_Email_Address Check (REGEXP_LIKE (email_address, '^(\S+)\#(\S+)\.(\S+)$'))
Constraint NN_Investor_Email_Address Not Null,
Account_Number Number(7,0) Not Null,
Constraint FK__Investor_Account_Number --Name of Constraint
Foreign Key (Account_Number) -- Foreign Key Column name
References Account(Account_Number)-- name of table and column trying to reference,
);
Here is an insert statement which fails the constraint.
INSERT INTO Investor (Investor_Number, First_Name, Last_Name, Street_Address, City, Province, Postal_Code, Area_Code, Phone_Number, Email_Address, Account_Number)
VALUES (1004, 'Tobias', 'Schneider', '10222 102 ST', 'Edmonton', 'AB', 'T5P 1W1', 780, 4997766, 'pellentesque#freenet.com', 7200);
It gives SQL Error:
ORA-02290: check constraint (ORCL2_21.CK_INVESTOR_POSTAL_CODE) violated
Specifying NULL constraint is simply useless. Column will allow nulls by default, so - no point in doing that.
You said that you have problems with CK_INVESTOR_POSTAL_CODE; I don't:
SQL> create table investor
2 ( Postal_Code Varchar2(7)
3 Constraint CK_Investor_Postal_Code Check
4 (REGEXP_like(Postal_Code,'[A-Z][0-9][A-Z][0-9][A-Z][0-9]'))
5 --Having problem getting postal code to work on test inserts code!!!!!!
6 );
Table created.
SQL> insert into investor values ('A1B2C3');
1 row created.
SQL> insert into investor values ('abcdef');
insert into investor values ('abcdef')
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CK_INVESTOR_POSTAL_CODE) violated
SQL> insert into investor values ('123');
insert into investor values ('123')
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CK_INVESTOR_POSTAL_CODE) violated
SQL> insert into investor values ('AAABBB');
insert into investor values ('AAABBB')
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CK_INVESTOR_POSTAL_CODE) violated
SQL>
Without providing what you did (i.e. what values you tried to insert into a table), it is difficult to guess what's wrong.
First, it's not clear what "getting it wrong" means. Are you getting an error or something? If so, it helps to show exactly what error you're getting.
Second, this works for me, in the sense that I can create the table, after removing the FK constraint on account_number, just because I don't have that table.
Third, You have several NULL constraints, but I assume those are supposed to be NOT NULL. Otherwise, they don't make sense.
Fourth, province should not be IN but probably LIKE.
I don't know what Canadian postal codes look like. Is A0A0A0 a valid postal code?
Personally, I'd get rid of the CHAR and use VARCHAR2 instead. Just never use CHAR. If your database is UTF-8, I'd also specify the columns with a length type, like VARCHAR2(25 CHAR).
Edit:
Your postal code has a space in it, but your regex does not allow them. You might make it '[A-Z][0-9][A-Z] [0-9][A-Z][0-9]', with a space between the third and fourth tokens..
Your sample postcode is 'T5P 1W1'. Your regex only enforces letters and digits, and doesn't allow for spaces. So either:
you need to change the postcode value so it is 'T5P1W1' or
you need to change the regular expression to include the space, e.g (REGEXP_like(Postal_Code,'[A-Z][0-9][A-Z] [0-9][A-Z][0-9]'))
Related
Could anyone experienced have a quick look at the following. I am not smart enough to resolve the system error just yet.
CREATE TABLE TestSubject (
test_subjectID NCHAR (6) NOT NULL PRIMARY KEY,
subject_name NVARCHAR (10) NOT NULL,
subject_address NVARCHAR (12) NOT NULL,
)
;
CREATE TABLE PhNumber (
subject_id NCHAR (6) NOT NULL,
ph_number NVARCHAR (20) NOT NULL,
PRIMARY KEY (ph_number),
FOREIGN KEY (subject_id) REFERENCES TestSubject (test_subjectID)
);
CREATE TABLE Test (
test_date DATETIME NOT NULL,
subject_id NCHAR (6) NOT NULL,
result NVARCHAR (10),
PRIMARY KEY (test_date),
FOREIGN KEY (subject_id) REFERENCES TestSubject (test_subjectID));
CREATE TABLE Place (
place_name NVARCHAR (10) NOT NULL PRIMARY KEY,
place_address NVARCHAR (8),
place_owner NVARCHAR (8)
);
CREATE TABLE VisitSubject (
v_date DATETIME NOT NULL,
v_number NVARCHAR (20) NOT NULL,
place_visit NVARCHAR (10) NOT NULL,
party_size INT,
PRIMARY KEY (v_date),
FOREIGN KEY (v_number) REFERENCES PhNumber (ph_number),
FOREIGN KEY (place_visit) REFERENCES Place (place_name));
And the populate script
INSERT INTO TestSubject
VALUES
('S001', 'Daniel Doppler', '5 Beetle Avenue Aberdeen'),
('S002', 'Florence West', '17 Green Crescent Dundee'),
('S003', 'Werner Flick', '25A Grubb Street Stonehaven'),
('S004', 'Tiffany Smith', '11 Green Crescent Dundee'),
('S005', 'Angela Ashe', '113 Wasp Street Aberdeen');
INSERT INTO Test
VALUES
('2020/08/05 00:00:00', 'S001', 'Negative'),
('2020/08/10 00:00:00', 'S002', 'Positive'),
('2020/08/17 00:00:00', 'S003', 'Negative'),
('2020/08/22 00:00:00', 'S004', 'Negative'),
('2020/08/22 00:00:00', 'S005', 'Negative'),
('2020/09/03 00:00:00', 'S001', 'Positive');
INSERT INTO PhNumber
VALUES
('S001', '07123-123456'),
('S002', '07777-111000'),
('S003', '07555-246810'),
('S004', '07101-484848'),
('S004', '07896-102304'),
('S005', '07777-534242');
INSERT INTO Place
VALUES
('Pink Lion Inn', 'Forfar', 'Sean Conran'),
('Irenes Hair Salon', 'Stonehaven', 'Irene Jones');
INSERT INTO VisitSubject
VALUES
('2020/08/01 00:00:00', '07123-123456', 'Irenes Hair Salon', '1'),
('2020/08/01 00:00:00', '07777-111000', 'Irenes Hair Salon', '2'),
('2020/08/25 00:00:00', '07123-123456', 'Pink Lion Inn', '4'),
('2020/08/25 00:00:00', '07493-285113', 'Pink Lion Inn', '2'),
('2020/09/10 00:00:00', '07555-246810', 'Irenes Hair Salon', '1'),
('2020/09/15 00:00:00', '07555-246810', 'Pink Lion Inn', '3');
I cannot populate the existing tables because of 2 errors -
String or binary data would be truncated
and
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Test__subject_id__286302EC". The conflict occurred in database "TAT_2012552", table "dbo.TestSubject", column 'test_subjectID'.
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__PhNumber__subjec__25869641". The conflict occurred in database "TAT_2012552", table "dbo.TestSubject", column 'test_subjectID'.
The first error means that you are trying to insert a value in a column where the data type length is smaller than the value. For example, in your VisitSubject table, the place_visit column can accept strings that have 10 characters or less. In your case, for example, value Irenes Hair Salon cannot be inserted because it's more than 10 characters.
The second error is thrown because subject_id values inserted in your tables Test and PhNumber are not existing in the table TestSubject. And why it is not existing in your table TestSubject ? Because SQL couldn't insert any row in this table because subject_name and subject_address values inserted have more characters than the data type length defined in your table.
Please first solve issue about inserting values longer than the data types definitions, and it should solve your foreign key issues then.
Let's start with the obvious error:
String or binary data would be truncated
This error is very much telling you the problem, you have a string value that is trying to be inserted into a column, however, it is too large and as such the value would be truncated. As a result the INSERT statement fails. If you're on a more recent version of SQL Server, you actually get even more verbose errors for this. There are actually 3 of these errors in your batch, such as:
String or binary data would be truncated in table 'YourDatabase.dbo.TestSubject', column 'subject_name'. Truncated value: 'Daniel Dop'.
Clearly you aren't using the latest version of SQL Server, or you would have shared that whole error, however, the old error do still tell you what table and column the error is on.
So let's have a look at the column YourDatabase.dbo.TestSubject.subject_name, which is defined as a nvarchar(10). Well looking at the INSERT, the first person's name is 'Daniel Doppler', which is more than 10 characters and hence the error. In fact, the entire INSERT statement will fail for every string value, as your subject_address column is defined as an nvarchar(12), yet the first value you try to INSERT is '5 Beetle Avenue Aberdeen' which is way more than 12 characters.
So how do you fix this? Fix your table's definition and increase the size of the columns; clearly 10 and 12 characters are not enough for a "subject's" name and address respectively.
So, what about the other errors such as:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Test__subject_id__29572725". The conflict occurred in database "YourDatabase", table "dbo.TestSubject", column 'test_subjectID'.
Well, this is actually a result of your prior error; your INSERT failed as you're trying to INSERT data that is too large for your columns and thus it isn't INSERTed. Then, when you get to the next INSERT statement the Foreign Key constraint (which has an obtuse name as you didn't give it one, but we'll come to that in a second) fails it's CHECK as there are no rows in the table dbo.TestSubject. Effectively the prior truncation error just compounds the problem.
As I mentioned, these errors happen multiple times, you have 3 truncation errors in that batch; meaning 3 INSERT statements fail due to the column being too small for the value to fit; you'll need to fix each of those tables definition so that they are an appropriate length for the data you are inserting. You also have 2 Foreign Key constrait failures, but these will likely disappear when you fix the table definitions.
As I mentioned, I do, however, recommend naming your constraints. You can do this by using an ALTER statement and creating the CONSTRAINT in there instead. For example:
CREATE TABLE dbo.PhNumber (subject_id nchar(6) NOT NULL,
ph_number nvarchar(20) NOT NULL);
ALTER TABLE dbo.PhNumber ADD CONSTRAINT PK_PhNumber PRIMARY KEY CLUSTERED (ph_number);
ALTER TABLE dbo.PhNumber ADD CONSTRAINT FK_PhNumber_TestSubject FOREIGN KEY (subject_id) REFERENCES dbo.TestSubject (test_subjectID);
This changes one the errors, about the Foreign Key failure, to the below; which is must more understandable due to the key's name:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_PhNumber_TestSubject". The conflict occurred in database "YourDatabase", table "dbo.TestSubject", column 'test_subjectID'.
Trying to build tables for a project in DB Browser and one of my tables is being created without any attribute columns, totally empty.
I've determined through trial, that the offending instruction is one of the foreign key assignments (specifically the one assigning EMPLOYEE.emp_years as a foreign key reference to RAISE.emp_years). By commenting out this line, the table builds completely, with all attribute columns. But I need this line.
CREATE TABLE PAYRATE (
rai_bump DECIMAL (2, 2) NOT NULL,
bas_basepay DECIMAL (2, 2) NOT NULL,
pay_rate DECIMAL (2, 2) NOT NULL,
PRIMARY KEY(rai_bump, bas_basepay)
);
CREATE TABLE BASEPAY (
emp_agerange CHAR(20) NOT NULL,
bas_basepay DECIMAL (2, 2) NOT NULL,
PRIMARY KEY(emp_agerange),
FOREIGN KEY(bas_basepay) REFERENCES PAYRATE(bas_basepay)
);
CREATE TABLE RAISE (
emp_years INTEGER NOT NULL,
rai_bump DECIMAL (2, 2) NOT NULL,
PRIMARY KEY(emp_years),
FOREIGN KEY(rai_bump) REFERENCES PAYRATE(rai_bump)
);
CREATE TABLE EMPLOYEE (
emp_num INTEGER NOT NULL,
emp_fname VARCHAR(20) NOT NULL,
emp_lname VARCHAR(20) NOT NULL,
emp_years INTEGER NOT NULL,
emp_agerange CHAR(20) NOT NULL,
PRIMARY KEY(emp_num),
FOREIGN KEY(emp_years) REFERENCES RAISE(emp_years), /* <-- offender */
FOREIGN KEY(emp_agerange) REFERENCES BASEPAY(emp_agerange)
);
The Employee table should have the 5 attributes, emp_num, emp_fname, emp_lname, emp_years, and emp_agerange. When I run my code without the offending line above, that is what I get, but with the line, the employee table is created but has no columns at all. I get no error messages. It says it runs successfully both with and without the offending line.
I figured out the cause. After having trouble while troubleshooting, getting errors any time I referred to the RAISE table, I got syntax errors. I got an inkling and looked up the word. Sure enough, RAISE if a reserved word in SQLite. It let me create a table with the name, but wouldn't let me refer to it because it thought I was referencing the RAISE function.
I've got a problem to insert some values into table.
Microsoft SQL server management shows that:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Players__Menager__55D59338". The conflict occurred in database
"TransferyProjekt", table "dbo.Menagers", column 'idMenager'.
My Create table script.
CREATE TABLE Menagers (
idMenager INT IDENTITY(1,1) NOT NULL,
[name] VARCHAR(30) NOT NULL CHECK (name LIKE '[A-Z]%'),
surname VARCHAR(30) NOT NULL CHECK (surname LIKE '[A-Z]%'),
phoneNumber VARCHAR(18) NOT NULL CHECK (phoneNumber LIKE '+[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'),
PRIMARY KEY (idMenager)
);
CREATE TABLE Players (
idPlayer INT IDENTITY(1,1) NOT NULL,
[name] VARCHAR(30) NOT NULL,
surname VARCHAR(30) NOT NULL,
age DATE NOT NULL check (DATEDIFF(year,age,GETDATE()) > 18),
club INT NOT NULL,
Menager INT NOT NULL,
PRIMARY KEY (idPlayer),
FOREIGN KEY (club) REFERENCES Clubs(idClub),
FOREIGN KEY (Menager) REFERENCES Menagers(idMenager)
);
My insert look like.
INSERT INTO Menagers VALUES
('Adil','Green','+232247832'),
('Wicky','Dock','+301494064'),
('Alead','King','+447499384'),
('Darmian','Dagoly','+445587849'),
('Kamila','Dobra','+958789278'),
('Mateusz','Jankowiak','+849383098'),
('Lendy','Day','+448902920'),
('Martin','Lloyd','+501044468'),
('Adam','Dosh','+045033739'),
('Cristian','Cosy','+307748735'),
('Andrew','Lloyd','+635875452'),
('Matias','Banega','+520091224'),
('Carl','Rossi','+196935415'),
('Michał','Rolnik','+156541588'),
('Denny','Nowsky','+231785387'),
('Micky','Elly','+125774609'),
('George','Taylor','+094371433'),
('Barack','Obama','+916764868'),
('Jin','Chan','+906765545'),
('Lee','Konsu','+608935829'),
('Adam','Kenzo','+417708081'),
('Bryan','Along','+939454178'),
('Robert','Leey','+183354912'),
('Tom','Vardy','+576176145'),
('Kevin','Betword','+721582207');
INSERT INTO Players VALUES
('Lionel','Messi','1986-07-13','23','4'),
('Cristiano','Ronaldo','1986-04-11','23','5'),
('Sergio','Ramos','1986-09-07','23','12'),
('Łukasz','Piszczek','1986-11-20','23','14'),
('Robert','Lewandowski','1986-12-01','2','13'),
('Michał','Pazdan','1986-06-01','3','23'),
('Łukasz','Trałka','1986-05-02','7','20'),
('Łukasz','Teodorczyk','1986-04-14','6','18'),
('Mariusz','Miley','1985-03-06','3','26');
You should define column names if your source table and destination table has different column counts or different order
INSERT INTO Menagers([name],surname, phoneNumber )
VALUES
('Adil','Green','+232247832'),
('Wicky','Dock','+301494064'),
....
INSERT INTO Players([name], surname, age, club, Menager )
VALUES
('Lionel','Messi','1986-07-13','23','4'),
('Cristiano','Ronaldo','1986-04-11','23','5'),
...
Your foreign key and primary key columns are INT type. But, you are having following SQL
INSERT INTO Players VALUES
('Lionel','Messi','1986-07-13','23','4')
where last column belongs to foreign key column and your value is string.
A foreign key is a reference to a unique value in a different table, and SQL will ensure "referential integrity" - which means it won't let you end you with "orphaned" key references. When you insert a value to a foreign key column it must be a null or a existing reference to a row in the other table, and when you delete, you must delete the row containing the foreign key first, then the row it references.
If you don't, you will get an error such as you describe.
So enter the row into the "main" table first, then enter the "dependant" table information second.
In FK column I added unfortunately referece to row who is not exists in table Managers...
('Mariusz','Miley','1985-03-06','3','26');
but I don't have 26'th row in table Managers (Blame me, now) :(
Evening all. I am fairly new to SQL but have been doing quite a bit of fooling around. I am following a guide I found online to learn SQL in 21 days and I am having a bit of trouble figuring out what the error I am receiving is causing.
I am trying to INSERT data into an existing table. The Primary Key for this table is AddressID. The data I am trying to enter is in the code below:
INSERT INTO [dbo].[Address]
(AddressID,Street,City,State,ZipCode)
VALUES
(1,'2400 Broadway','New York','NY',11201),
(2,'320 21st Street','Atlanta','GA',303),
(3,'439 Skyline Blvd','Seattle','WA',98101),
(4,'56 Park Avenue','Dallas','TX',75201);
GO
I keep getting this error:
Msg 2627, Level 14, State 1, Line 2 Violation of PRIMARY KEY
constraint 'PK_Address'. Cannot insert duplicate key in object
'dbo.Address'. The duplicate key value is (1).
I have tried just about everything I can think of but I am unable to get my table updated. My column names at under the INSERT INTO portion are correct and my VALUES are also correct. I did find that I can use a single INSERT statement to get my data in the table. Originally I was using 4 separate statements.
What am I doing wrong?
In this case I think it's safe to let the database choose the primary key by not specifying it. There's probably already data in the table.
INSERT INTO [dbo].[Address]
(Street,City,State,ZipCode)
VALUES
('2400 Broadway','New York','NY',11201),
('320 21st Street','Atlanta','GA',303),
('439 Skyline Blvd','Seattle','WA',98101),
('56 Park Avenue','Dallas','TX',75201);
GO
From the error message it is very clear that already AddressID = 1 exist in the table since you have a primary key on AddressID you cannot insert duplicate values.
Try this query to insert into the table
INSERT INTO [dbo].[Address]
(Street,City,State,ZipCode)
SELECT Street,City,State,ZipCode
FROM ( VALUES (1,'2400 Broadway','New York','NY',11201),
(2,'320 21st Street','Atlanta','GA',303),
(3,'439 Skyline Blvd','Seattle','WA',98101),
(4,'56 Park Avenue','Dallas','TX',75201))
v(addressid, street, city, state, zipcode)
WHERE NOT EXISTS (SELECT 1
FROM [dbo].[address] A
WHERE a.addressid = v.addressid)
If addressid columns has identity property then remove the addressid column from insert column list and select list.
What you doing wrong is:
You already have AddressId (1) in your table Address table.
Primary key should be unique. You cannot insert duplicate values in the primary key column.
What you can probably do is:
update the existing value and insert the new values. That means update the row with AddressId 1 and insert new rows with new AddressIds.
It's better you let the Sql Server decide on your primary key value by creating `identity column'. You could create identity column while creating a table as follows:
CREATE TABLE [dbo].[Address]
(
[AddressId] [int] IDENTITY(1,1) NOT NULL,
[OtherColumns] [int] NULL,
CONSTRAINT [PK_Address] PRIMARY KEY CLUSTERED (AddressId ASC)
)
Please note that, if you have created a table with Idenity column, you do not need to supply any values during insert operation because Sql Server implicitly creates and inserts that values for you.
Primary Keys have to be unique. If AddressID is your primary key you cannot have two rows in your table that have the same AddressID number. Primary Keys are usually set automatically so you don't have to set them yourself.
Think of the Primary Key as a unique identifier for each row. The duplicate key error is telling you that you already have a row in your address table that has an AddressID value of 1. To avoid these errors you should set your AddressID column to IDENTITY and not worry about setting the value. Try inserting your records without setting the AddressID. Something like so:
INSERT INTO [dbo].[Address]
(Street,City,State,ZipCode)
VALUES
('2400 Broadway','New York','NY',11201),
('320 21st Street','Atlanta','GA',303),
('439 Skyline Blvd','Seattle','WA',98101),
('56 Park Avenue','Dallas','TX',75201)
('56 Park Avenue','Dallas','TX',75201);
GO
I have two columns. SQL is:
CREATE TABLE tdegree
(
degree varchar(25) NOT NULL primary key
)
CREATE TABLE tstudy
(
study varchar(25) NOT NULL unique,
degree varchar(25) NOT NULL FOREIGN KEY REFERENCES tdegree (degree)
)
as shown in below figure I want to add record
master it
mphil it
but not
master it
master it
If I apply unique constraints on study field then it does not allowed me to add
master it
mphil it
Which constraints i have to apply?
If I understand correctly, you want the combination of study and degree to be unique, but values can be repeated in individual columns e.g. Row 1 is Master + IT and Row 2 is MPhil + IT, so that both rows are unique but study column has duplicate value IT. In that case, you need to add a unique constraint on both columns together like so:
alter table tstudy add constraint cunique unique(study,degree)
Note that you also need to change the definition of your tstudy table and remove the unique constraint on study column, otherwise you will get a unique constraint violation error, even after adding the above constraint:
CREATE TABLE tstudy
(
study varchar(25) NOT NULL,
degree varchar(25) NOT NULL FOREIGN KEY REFERENCES tdegree (degree)
)