SQL Insert into table with 2 non-unique primary keys - sql

I have a table that I need to insert data into.
The table Sales has 4 columns
CustomerValueType_id (int)
Customer_id (int)
Value (NVARCHAR)
Customer_name (NVARCHAR)
The CustomerValueType_id, Customer_id are foreign keys that are not-unique, CustomerValueType_id matches to a value type, while Customer_id matches to the Customer_name.
I need to add additional customer data into the Valuecolumn but how do I ensure that the data matches to the correct CustomerValueType_id and Customer_id and each customer name has to be repeated in the Customer_name
Sales Table

You are trying to do denormalization.
Ideally, in the normalized design, you will just store, parent_ids in
the child table. If you want to see parent_name fields, you have to
get them based on JOIN conditions.
But, here as you are storing both id, name in the child table, I would suggest you to create composite Foreign key in the child table, so that the combination is always present. Also, make this combination as composite primary key in the parent table.
-- Parent Table PRIMARY KEY
ALTER TABLE dbo.CustomerValueType
ADD CONSTRAINT PK_CustomerValueType
PRIMARY KEY CLUSTERED (CustomerValueType_id, Value);
GO
--Child Table FOREIGN KEY
ALTER TABLE dbo.Sales
ADD CONSTRAINT FK_Sales_CustomerValueType
FOREIGN KEY (CustomerValueType_id,Value)
REFERENCES dbo.CustomerValueType(CustomerValueType_id,Value);
GO

Related

why I am getting error trying to add Foreign key to table

I Not able to add foreign key to tbl1 referencing tbl2 (Desc), here are the two tables :
please notice Tbl1 includes all values,tbl2 Has more values that doesn't necessarily exists in tbl1
Error(Msg 1776): There are no primary or candidate keys in the referenced table 'tbl2' that match the referencing column list in the foreign key 'fk_desc'.
tbl1:
alter table tbl1 add constraint pk_desc primary key (desc)
The Error:**alter table tbl1 add constraint fk_desc foreign key (desc)
references tbl2(desc)**
Desc
Astrogator
Geologist
Technician
tbl2:
alter table tbl2 add constraint pk_canid_desc primary
key(id,desc)
ID
Desc
1001
Astrogator
1001
Geologist
1001
Technician
2003
Biochemist
thank you for the help,
you cant make Desc that at table tbl2 as a FK while it contains values not exists at the table tbl1
Adding a foreign key is different depending on the flavor of SQL your using. For sql server you would bring up the parent db in SSMS using table design. Select Foreign key relationships and add a new relationship. From there select other table and column which has foreign key. Keep in mind that there needs to exist a foreign key for each Primary record or you will get an error.

How to create associative table where one of the fields is not primary key?

I am structuring a postgres database.
I have two tables, products (coke) and optional (with ice, lemon ...), that is, a relationship many to many.
An associative table is usually built using the primary keys of the tables, correct? However, in my case, there is a specific feature ... due to some imports from other databases...I have two ids fields (id and "externalId"), one primary key and one common ... one is the local id of my bank and the other represents the id that the item has in the bank from which it was imported.
I need an associative table between "externalId" and a primary key from another table.
ExternalId is not a primary key...
ALTER TABLE public.opcional_produto
Add
CONSTRAINT idproduto_fkey FOREIGN KEY (prod_id) REFERENCES public.produto (prod_idExt)
ERROR: there is no unique constraint matching given keys for
referenced table "produto" SQL state: 42830
How can I do?
If externalid is unique, you should create a unique constraint:
ALTER TABLE produto ADD UNIQUE (externalid);
Ideally it should also be not nullable:
ALTER TABLE produto ALTER externalid SET NOT NULL;
Now it can be used as target of a foreign key.

Creating unique primary key to ignore duplicates

I have a main large table which I have had to put into 3rd normal form and into smaller tables (with primary and foreign keys linking them). The table is about renting books.
I have a customer table which I need to create a primary key for. In the main large table there are duplicates of the customer_id, as the table as a whole is for renting the books, so one customer may have more than one renting.
The table I am currently trying to add a primary key for will not have any nulls or duplicates, however i am unsure how to create the primary key for this without the error- unsure how to make it unique.
CREATE TABLE customer AS
SELECT cust_id, country_id, name, address, postcode
FROM BOOKS
WHERE cust_id != 0;
ALTER TABLE customer
ADD PRIMARY KEY (cust_id);
Is anyone able to help me in how to create the primary key on my customer table, but just taking each unique cust_id from the main table.
In SQL Server the straightforward way to add unique keys is to use IDENTITY. Identity fields are integer fields that auto populate successive values by a specified start value and interval. If you don't specify the interval it will start at 1 and increase the value by 1 each time a value is assigned.
While it's usually done when creating a table, you can do it in your ALTER TABLE step, and it will assign values when added to an existing table. I've explicitly specified the start value and interval that matches the default to show the syntax :
ALTER TABLE customer
ADD cust_id int not null PRIMARY KEY IDENTITY(1,1)

Relationship between composite keyed table & non primary key table

I have two tables named ORDER_HEAD and ORDER_DETAIL, following is their structure.
ORDER_HEAD:
ORD_ID (PK)
ORD_TYPE (PK)
ORD_DATE
ORD_NET_TOTAL
ORDER_DETAIL:
ODD_ID
ODD_LINE_NO
ODD_PRODUCT_ID
ODD_QTY
I want to form a relationship between the ORD_ID in ORDER_HEAD & ODD_ID in ORDER_DETAIL table. But SQL Server shows an error message:
primary key or unique constraint must be defined for table before it can participate in a relationship
Why am I getting this error ? Is there a way to perform a join between these two columns or is there a problem in my db design ?
If you want to create a relationship from Composite primary key then any reference should also include all the column's in Composite primary key
Schema of ORDER_DETAIL should be
ORDER_DETAIL
============
ODD_ID (Fk)
ORD_TYPE(Fk) -- you need to add this column
ODD_LINE_NO
ODD_PRODUCT_ID
ODD_QTY
Create Foreign key like this.
ALTER TABLE ORDER_DETAIL
ADD CONSTRAINT FK_ORDER_DETAIL
FOREIGN KEY(ODD_ID, ORD_TYPE) REFERENCES ORDER_HEAD(ODD_ID, ORD_TYPE)
UPDATE
After rethinking the problem I think you should achieve your goal by adding reference column ODD_TYPE (like user #NoDisplayName stated) and creating composite PK for your table ORDER_DETAIL consisting of 3 columns (ODD_ID, ODD_TYPE, ODD_LINE_NO), then it would be:
ORDER_DETAIL
============
ODD_ID (PK)
ODD_TYPE (PK)
ODD_LINE_NO (PK)
ODD_PRODUCT_ID
ODD_QTY
in SQL it could be:
ALTER TABLE ORDER_DETAIL ADD CONSTRAINT PK_Order_Detail PRIMARY KEY NONCLUSTERED (ODD_ID, ODD_TYPE, ODD_LINE_NO)
Then, in ORDER_DETAIL table for specific pair (ODD_ID, ODD_TYPE) you would have records being its order lines.
I think that after removing the previous PK, adding the column and setting the above key (even in visual editor) you shouldn't have problems when creating FK between the two tables and mapping the proper columns together.

primary key to foreign key to foreign/primary

there are tables in database like
tbl_items
item_id item_batch item_name
(primay key = item_id+item_batch)
tbl_transaction(orders)_header
ordre_id employe_id date
(primary key= order_id)
tbl_transaction_(orders)detail
(id)blind order_id item_code item_batch item_qty
(primary key= blind mean identy column) (foreign key = item_code+item_batch from tbl_items)
tbl_warehouse
item_code Item_batch item_qty
primary key(item_code+item_batch)
confusion here
i--foreign key(item_code+item_batch to item_code+item_batch from tbl_transaction_detial )
or this is correct
ii--
foreign key(item_code+item_batch to item_code+item_batch from tbl_items )
the process is as fellow user create new bill whose id and current date will be stored in transaction_header and the item customer buy their detail will be stored in transaction details and then update warehouse table
now if the record exist in transaction header then update warehouse
according to this what will be the correct foreign key relation ship i or ii
So sorting out your first confusion:
Foreign Key of transaction_table will point to Primary key of table_item.
or in better way you can say that.
Foreign Key of transaction_table references Primary key of table_item.
And as per your question:
i) Your transaction_header will not contain any Foreign Key. I mean it do not need any Foreign Key.
ii) Foreign Key from transaction_detail will reference to Primary key of table_item.
iii) Foreign Key of transaction_detail will reference to Primary Key of warehouse.
As change in the transaction_detail is causing changes in warehouse and item_table.
For better understanding read this.