I'm trying to create a sql table in net frame work in VS that has room and user id ,but I want that only one of each combination can exist in the table:
Want:
room --- user id
1 2
1 3
3 2
2 1
1 1
3 1
Dont want:
room --- user id
1 2
1 2
how can I make it so that only unique combination can be entered?
You can enforce uniqueness using a unique constraint or index:
create unique index unq_t_room_userid on t(room, user_id);
or:
alter table t add constraint unq_t_room_userid
unique (room, user_id);
Looks like you want Room, UserId to be the PRIMARY KEY on that table.
CREATE TABLE Occupancy
(
RoomId INT NOT NULL
,UserId INT NOT NULL
,CONSTRAINT PK_Occupancy PRIMARY KEY CLUSTERED (RoomId,UserId)
)
When you try to insert a duplicate value:
INSERT dbo.Occupancy (RoomId,UserId)
VALUES
(1,1)
,(1,2)
,(1,1)
GO
You will get a message like this:
Violation of PRIMARY KEY constraint 'PK_Occupancy'. Cannot insert
duplicate key in object 'dbo.Occupancy'. The duplicate key value is
(1, 1).
Related
I'm creating a project for a hotel reservation, and I want to insert multiple values into a column which is a foreign key in a table that has a primary key column but it's not possible to insert a duplicate key when it's primary and it's not possible to insert different values than the values that inserted in the main column that I used it as foreign key in this table, so what can I do?
Clarification
I have a table for reservation and another table for hotel services, there is a column in [Reservation] table which is the primary key (ReservationID) and there is a column in the [Hotel_Services] table that I used as a foreign key to the [Reservation] table which is (ServiceID).
What I want is to insert multiple service IDs into each reservation to indicates the services that each guest has added to his reservation, how can I do this?
Table #1: Reservation
`ReservationID` (primary key) e.g 10,20,30
Table #2: Hotel_Services
`ServiceID` (foreign key to `Reservations`) e.g 1, 2, 3
Desired result: add multiple service IDs into each reservation
e.g:
Reservation 10 has 1,2 services
Reservation 20 has 1,3 services
Reservation 30 has 2,3 services
You need a table ReservationServices, defined something like this:
create table ReservationServices (
ReservationServiceId int identity primary key,
ReservationId int not null references reservations(reservationid),
ServiceId int not null references services(serviceid);
);
Then your data would look like:
ReservationServiceId ReservationId ServiceId
1 10 1
2 10 2
3 20 1
4 20 3
. . .
So, inserting a new service for a reservation is, well, as simple as inserting a new row in this table.
I have the following tables:
TRANSACTIONS
id | amount
------------------
1 | 100
2 | -100
3 | 250
4 | -250
TRANSACTION_LINKS
id | send_tx | receive_tx
---------------------------
1 | 2 | 1
2 | 4 | 2
The send_tx and receive_tx columns in the transaction links table use foreign keys pointing to the ID of the transactions table.
This is how I create the transaction links table
CREATE TABLE IF NOT EXISTS transaction_links
(
id BIGSERIAL PRIMARY KEY,
send_id INT NOT NULL UNIQUE REFERENCES transactions(id) ON DELETE
RESTRICT,
receive_id INT NOT NULL UNIQUE REFERENCES transactions(id) ON DELETE
RESTRICT
);
I want to create a unique constraint over both send_tx and receive_tx, meaning that if transaction id 1 is found in the receive_tx column, then
no other transaction link can have the receiving_tx = 1
no other transaction link can have the sending_tx = 1
I know that I can have a unique constraint on each column separately, but that only solves my first problem
EDIT:
essentially, if I insert (1,2) into transaction links, then inserting (1,3) or (3,1) or (4,2) or (2,4) should all be rejected
Also, in my design, the transactions table contains many more columns than what is shown here, I've only included the amount for simplicity's sake.
You can use an exclusion constraint which only requires a single index:
alter table transaction_links
add constraint check_tx
exclude using gist ( (array[send_id, receive_id]) with &&);
The && operator is the "overlaps" operator for arrays - which means "have elements in common, regardless of the order of the elements in the array. In this case the constraint prevents to insert any row where any value of (send_id, receive_id) appears in some other row of the table (regardless of the column).
However, you need the intarray extension for that.
Online example: https://rextester.com/QOYS23482
How do I add constraint to guard that a primary key could only be referenced once?(It could be referenced in two tables)
Each reference should have a unique value out of the primary key.
Table A
----------------------
id
1
2
3
4
Table B
----------------------
id a_id (foreign key to table A.id)
1 2
2 3
Table C
----------------------
id a_id (foreign key to table A.id)
1 1
I want something to happen to give error when try to insert a_id = 2 into table C as its used in table B already.
You can use an INSERT, UPDATE trigger on each of the child tables to ensure that the PK of the parent table that is about to be inserted or updated does not already exist in the other child table.
What you are trying to do requires another table D, that will help unify the references to A.
Table D will contain its own primary key ( Id ), a reference to table A with a UNIQUE constraint on it (call it AId ), and a third column (called "RowType") to indicate to which of the child tables (B or C) the row corresponds. You can make this column to be of type int, and assign value "0" for B and "1" for C, for example.
Then in table B you add a foreign key to D.Id, AND another column "BRowType" as foreign key to D.RowType; then you define a constraint on this column, so it can only have the value '0' ( or whatever value you have decided to correspond to this table).
For table C your constraint will limit the values to '1'.
Or course, in order to insert a record into B or C you first need to create a record in D. But once you have a record in B that references a record in D, which in turn links to a record in A, you will no longer be able to create a record in C for the same line in A - because of the UNIQUE constraint on D.AId AND the constraint on C.BRowType.
If I understand the question correctly, it sounds like you need to add a unique constraint on the column of each table that references your primary key.
For example:
Table A
----------------------
id (primary key)
1
2
3
Table B
----------------------
id a_id (foreign key to table A.id)
1 2
2 3
Set the a_id column to be UNIQUE and that way you can ensure that the primary key from Table A is not used twice. You would do that in each table which references A.id
If you want to avoid using triggers, you could create a table X with id and a unique constraint on it.
In each transaction in which you insert a record into B or C you have to insert into X as well. Both insertions will only be possible if not yet in the other table.
I tired to delete the occurrences of the values which the insert stmt was trying to insert
in the dependent table.
delete from BSC_UR_RE_AN
where AN_ID in (1084,1083,1088,1087,1121,1122,1123,1094,5010,
1239,1242,70187,7001,7002,1284,1285)
But no luck, I got the following error:
The INSERT statement conflicted with the FOREIGN KEY constraint
"BSC_U_RA_AN_FK". The conflict occurred in database "DMDB", table
"dbo.BSC_AN", column 'AN_ID'.
That error means that ANAG_ID value you're trying to insert as FOREIGN KEY doesn't exists on the related table. So, you should not delete it, you should insert it if it's missing.
Edit:
You should have a clear view of your tables design, examining the constraint of the tables you're trying to insert into.
As example, a Foreign Key constraint usually refers to a Primary Key of another table.
The error you see is because you're trying to inserd an invalid value (eg. not exists in the master table).
An example:
CREATE TABLE MasterTable (
ID int NOT NULL PRIMARY KEY,
Name varchar(50)
)
CREATE TABLE MasterTableValues (
IDMasterTable INT REFERENCES MasterTable(ID), --FOREIGN KEY
Value varchar(50)
)
Let's assume you have this data in MasterTable:
1 FirstDate
2 SecondData
3 ThirdData
5 FifthData
Now, you can insert these values in MasterTableValues:
1 SomeValue
1 SomeOtherValue
3 SomeValue
But CANNOT insert this value:
4 SomeValue
because the key ID = 4 don't exist in MasterTable
EmpID DeptID
1 1
1 2
2 1
3 2
4 5
5 2
1 1
2 1
I would like to have a constraint that will make sure that the pair of field is always unique ,such data as last two shown in the example should not be insert-able into the table .in the above table
please note that last two rows are duplicates ,I would like to prevent such data from occuring .
How do I achieve this in sqlserver 2005.Thanks
ALTER TABLE <YourTable, sysname, Emp>
ADD CONSTRAINT <YourConstraintName, sysname, uix>
UNIQUE NONCLUSTERED (EmpID,DeptID)
(Paste into SSMS and use (CTRL + Shift + M))
Or to do this at table creation and as it sounds as though there is no alternative key use.
CREATE TABLE EMPLOYEE_DEPARTMENT(
EmpID int NOT NULL REFERENCES EMPLOYEE(EmpID),
DeptID int NOT NULL REFERENCES DEPARTMENT(DeptID),
CONSTRAINT PK_EMPLOYEE_DEPARTMENT PRIMARY KEY CLUSTERED (EmpID ASC,DeptID ASC)
)
After you've gone through and removed the duplicates, run the following (substituting appropriate names)
ALTER TABLE table ADD CONSTRAINT UQ_EmpID_DeptID UNIQUE (EmpID,DeptID)
Or when creating your table:
CREATE TABLE T1 (
EmpID int not null,
DeptID int not null,
/* Other Columns */
constraint PK_T1 PRIMARY KEY (EmpID,DeptID)
)
(May as well make it the primary key, unless you've got another one in the table)
ALTER TABLE dbo.YOURTABLE ADD CONSTRAINT IX_YOURTABLE UNIQUE NONCLUSTERED (EmpID, DeptID)
select empID, deptID from table
group by empID, deptID
EDIT:
If you are saying this data must be unique in table itself, i.e. The insertion of duplicates should not be allowed, then you need to define a composite key (empID, deptID) on this table.
alter table <tablename> add constraint <compositekeyname> primary key (empID, deptID)