How to use value generated by GENERATE_UNIQUE() function as foreign key? - sql

I trying to implement the example from this manual Generating Unique Values in DB2 Universal Database but encountered the following problem.
I've two tables,
CREATE TABLE PC_LIST (
PC_ID CHAR(13) FOR BIT DATA NOT NULL,
PC_NAME VARCHAR(100) NOT NULL
PRIMARY KEY (ID)
);
And second table
CREATE TABLE PC_DATA (
ID CHAR(13) FOR BIT DATA NOT NULL,
PC_ID CHAR(13) FOR BIT DATA NOT NULL,
PC_NAME VARCHAR(100) NOT NULL
PRIMARY KEY (ID),
FOREIGN KEY (PC_ID) REFERENCES PC_LIST(PC_ID)
);
I add records to first table PC_LIST without any issues, and use inside INSERT query GENERATE_UNIQUE() function, everything works fine.
When I try to add a record to the second table and copy a value from PC_LIST.PC_ID as is I get an error Value "20150408131401000109000000 " is too long..
When I added a cast like following: CAST('20150408131401000109000000' AS CHAR(13) FOR BIT DATA) I get an error that The INSERT or UPDATE value of the FOREIGN KEY is not equal to any value of the parent key of the parent table.
What am I doing wrong?
Thank you.
UPDATE:
This code I use to insert data in PC_DATA
INSERT INTO PC_DATA
(
ID,
PC_ID,
PC_NAME
) VALUES (GENERATE_UNIQUE(), CAST('20150408131401000109000000' AS CHAR(13) FOR BIT DATA) ,'anatoly-pc');
Of course that PC_ID I've taken from PC_LIST table where it exists.

Related

How do I select insert into select a table which already has values in the primary key column without adding new rows?

I'm working on a database for my school project in which I have to produce a functional database by normalizing sample tables given to us.
One table I'm having trouble with is itineraries. I produce 3 tables from the normalization which are "Destinations", "Itineraries" and "Itinerary_Destinations".
The code for Destinations is:
create table Destinations
(
DestinationID varchar(5) primary key,
Name varchar(45)
);
The code for Itineraries is:
create table Itineraries
(
ItineraryID varchar(5),
Name varchar(45)
);
The code for the last table is:
create table Itinerary_Destinations
(
DI varchar(5) primary key,
ItineraryID varchar(5) foreign key references Itineraries(ItineraryID),
Itinerary_Name varchar(45),
DestinationID varchar(5) foreign key references Destinations(DestinationID),
Destination_Name varchar(45)
);
Data has already been inserted into all 3 tables with the exception of 'Destination_Name' and 'Itinerary_Name' columns. The code I'm attempting to use is returning as error. The code is shown below.
insert into Itinerary_Destinations (Itinerary_name)
select Name from Itineraries where
Itineraries.ItineraryID = ItineraryID;
The error it returns is
Msg 515, Level 16, State 2, Line 1 Cannot insert the value NULL into
column 'DI', table 'DDDAssignment.dbo.Itinerary_Destinations'; column
does not allow nulls. INSERT fails. The statement has been terminated.
Is there a method to accomplish the task of inserting the Destination_Name and Itinerary_Name without creating new records that require primary keys?
Or should I do it manually?
If you want to modify records which already exist, then you should be using an UPDATE rather than an INSERT:
UPDATE a
SET Itinerary_name = b.Name
FROM Itinerary_Destinations a
INNER JOIN Itinerary_name b
ON a.ItineraryID = b.ItineraryID;
But, if you do have some data which is not already logically associated with the Itinerary_Destinations table, then using an insert is appropriate.
use coalesce funtion in case null it will insert blank string, as your column does not allow null value thats why you got that error in your query
insert into Itinerary_Destinations (Itinerary_name)
select coalesce(Name,' ') from Itineraries where
Itineraries.ItineraryID = ItineraryID;

Why does the zipcode fail the check constraint?

I feel like I am probably missing something really simple, but I really can't figure out what I'm doing wrong. I'm trying to use a check constraint to make sure zipcodes are 5 digit numbers, but the check restraint keeps failing. Here is the table creating with the constraint:
Create Table Students (
StudentID Int Primary Key Identity(1,1)
StudentNumber nVarchar(100) Unique Not Null,
...
StudentZipCode nChar(10) Not Null
)
Go
Alter Table Students Add Constraint chZipCode
CHECK (StudentZipCode LIKE '[0-9][0-9][0-9][0-9][0-9]' OR StudentZipCode
Like '[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]')
Go
Codes like 12345-6789 work, but when I try to insert the values like '12345' or '01234' it gives me this error:
The INSERT statement conflicted with the CHECK constraint "chZipCode". The conflict occurred in database ..., table "dbo.Students", column 'StudentZipCode'.
It fails because you defined the zip code as a char() instead of a varchar(). Hence, it has a bunch of spaces padding it out.
So, define it as:
Create Table Students (
StudentID Int Primary Key Identity(1,1),
StudentNumber nVarchar(100) Unique Not Null,
StudentZipCode nVarChar(10) Not Null,
CHECK (StudentZipCode LIKE '[0-9][0-9][0-9][0-9][0-9]' OR
StudentZipCode LIKE '[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]')
);
Then '12345' works, because it matches the first of the LIKE patterns.
'012344' does not work, because no pattern has six digits in a row.
Here is a SQL Fiddle.

I can't insert null on a Foreign Key

I've tried to search but nothing works, and I don't know what to do.
There's a table with two foreign keys, one of which can be null. According to what I've searched, it's perfectly fine to have null foreign keys. But no matter what, when I try to insert a null in that value, it fails. It says:
*Cause: A foreign key value has no matching primary key value.
*Action: Delete the foreign key or add a matching primary key.
Here is the code of the table. The FK that I want to be null is idPedido
CREATE TABLE PAGOS(
fechaLimite DATE,
cuantia NUMBER NOT NULL,
fechaInicio DATE DEFAULT SYSDATE,
fechaLiquidacion DATE,
idPago VARCHAR(8) NOT NULL,
dni VARCHAR(14) NOT NULL,
tipoPago VARCHAR(7) DEFAULT 'OTRO' CHECK(tipoPAGO IN('MENSUAL','PEDIDO','OTRO')),
idPedido VARCHAR2(10),
PRIMARY KEY(idPago),
FOREIGN KEY(dni) REFERENCES MIEMBROS ON DELETE SET NULL,
FOREIGN KEY(idPedido) REFERENCES PEDIDOS ON DELETE SET NULL
);
There are some triggers and such to add sequences for the idPago value.
Here is the code of the procedure that creates a new item to the table:
create or replace PROCEDURE CREAR_PAGO(
new_fechaLimite IN PAGOS.fechaLimite%TYPE ,
new_cuantia IN PAGOS.cuantia%TYPE,
new_fechaInicio IN PAGOS.fechaInicio%TYPE,
new_fechaLiquidacion IN PAGOS.fechaLiquidacion%TYPE,
new_dni IN PAGOS.dni%TYPE,
new_tipoPago IN PAGOS.tipoPago%TYPE,
new_idPedido IN PAGOS.idPedido%TYPE
)
IS
BEGIN
INSERT INTO PAGOS(fechaLimite,cuantia,fechaInicio,fechaLiquidacion,dni,tipoPago,idPedido) VALUES(new_fechaLimite,new_cuantia,new_fechaInicio,new_fechaLiquidacion,new_dni,new_tipoPago,new_idPedido);
END CREAR_PAGO;
And here is me trying to insert a new element:
execute CREAR_PAGO('01012020',40,'01012010',null,49035480D,null,null);
I've already tried to put both "NULL" and "DEFAULT NULL" in the table code after idPedido's type and nothing works
Please I need help
It looks like the primary key for your table is idPago, but I don't see it in your insert statement. If that is the case, it would appear that your issue is trying to add a record with no primary key...not that the foreign key is null.

SQL Server 2008 Foreign Keys that are auto indexed

Are Foreign Keys in SQL Server 2008 are automatically indexed with a value? For Example. if I add a value in my Primary key (or auto incremetend) in may parent table will the table that has a foreign key referenced to that key will automatically have the same value? or I Have to do it explicitly?
No, if you create a foreign key in a child table, it will not automatically get populated when a parent row gets inserted. If you think about this it makes sense. Let's say you have a table like:
CREATE TABLE dbo.Students
(
StudentID INT IDENTITY(1,1) PRIMARY KEY,
Name SYSNAME
);
CREATE TABLE dbo.StudentLoans
(
LoanID INT IDENTITY(1,1) PRIMARY KEY,
StudentID INT FOREIGN KEY REFERENCES dbo.Students(StudentID),
Amount BIGINT -- just being funny
);
What you are suggesting is that when you add a row to Students, the system should automatically add a row to StudentLoans - but what if that student doesn't have a loan? If the student does have a loan, what should the amount be? Should the system pick a random number?
Typically what will happen in this scenario is that you'll be adding a student and their loan at the same time. So if you know the loan amount and the student's name, you can say:
DECLARE
#Name SYSNAME = N'user962206',
#LoanAmount BIGINT = 50000,
#StudentID INT;
INSERT dbo.Students(Name)
SELECT #Name;
SELECT #StudentID = SCOPE_IDENTITY();
INSERT dbo.StudentLoans(StudentID, Amount)
SELECT #StudentID, #LoanAmount;

Foreign Key is null when insert using Stored Procedure

I've created a insert stored procedure with two tables like in the exapmle:
Table NameAge
CREATE TABLE [dbo].[Assignment3_NameAge]
(
userID int PRIMARY KEY IDENTITY(1,1),
Name varchar(255) NOT NULL,
Age int NOT NULL
)
Table Hobbies
CREATE TABLE [dbo].[Assignment3_Hobbies]
(
hobbiesID int Identity(1,1) Primary Key,
userID int Foreign Key references Assignment3_NameAge(userID),
hobbies varchar(255) NOT NULL,
)
Insert Stored Procedure
CREATE PROCEDURE [dbo].p_Assignment3Join_ins
#Name nvarchar(100),
#Age int,
#Hobbies nvarchar(100)
AS
INSERT INTO [TABLE].[dbo].[Assignment3_NameAge]
([Name]
,[Age])
VALUES (#Name,#Age)
INSERT INTO [TABLE].[dbo].[Assignment3_Hobbies]
([Hobbies])
VALUES (#Hobbies)
The problem is that when i run the stored procedure the table Hobbies has a null value for userid(the foreign key)
What am i doing wrong?
You should provide the key of the Assignment3_NameAge value you want to insert into Assignment3_Hobbies.
If you want the last inserted you can use SCOPE_IDENTITY() from SQL Server(if you're using SQL Server) or equivalent. It will give you the last inserted value from Assignment3_NameAge
I am guessing this is SQL Server based on the IDENTITY column. Correct?
The first insert creates a user, but there is no user ID being set on the insert of the hobby. You need to capture the identity value from the first insert to be used in the second insert. Have you gon over the system functions available?
You're not supplying a value for it, SQL won't automagically fill the value in for you even though you've created a Foreign Key relationship. It's your job to populate the tables.