![]() | |
![]() |
| | Thread Tools | Display Modes |
#1
| |||
| |||
|
#2
| |||
| |||
|
|
How do I force a condition based on multiple rows? |
|
I want the necessary rows to be entered in a batch. As a simple example, what would be the coding of the constraint in this case following? create table Symmetric ( a int not null, b int not null ) Constraint: If (x,y) is in Symmetric, then (y,x) is also in Symmetric. |
#3
| |||
| |||
|
|
Gene Wirchenko (genew (AT) ocis (DOT) net) writes: How do I force a condition based on multiple rows? Generally, you need to use a trigger. |
|
I want the necessary rows to be entered in a batch. As a simple example, what would be the coding of the constraint in this case following? create table Symmetric ( a int not null, b int not null ) Constraint: If (x,y) is in Symmetric, then (y,x) is also in Symmetric. Assuming that (a, b) is the primary key, this can be enforced with a constraint: CREATE TABLE Symmetric ( a int NOT NULL, b int NOT NULL, CONSTRAINT pk PRIMARY KEY (a, b), CONSTRAINT fk FOREIGN KEY (b, a) REFERENCES Symmetric (a, b) ) |
#4
| |||
| |||
|
|
Giving another example, suppose it must be that there are an odd number of rows of a type of entry. create table EvenSteven ( pk varchar(10) not null, contrivance int not null ) In this case, there must be an odd number of rows for each value of contrivance. Suppose we have pk contrivance A 5 B 7 C 6 D 5 E 5 F 5 Adding G 6 H 7 would be an error (2 6's in total), but adding G 6 H 7 I 6 would be fine. Must I scan through the table and Inserted for each contrivance value, or is there a better way? |
#5
| |||
| |||
|
|
Dear SQL'ers: How do I force a condition based on multiple rows? I want the necessary rows to be entered in a batch. As a simple example, what would be the coding of the constraint in this case following? create table Symmetric ( a int not null, b int not null ) Constraint: If (x,y) is in Symmetric, then (y,x) is also in Symmetric. Anyone adding rows would have to do it in a batch: insert into Symmetric (a,b) values (3,5), (5,3) I am hoping that there is a simple answer that I am overlooking. Right now, all I can think of is to scan both Symmetric and the batch (Inserted). Sincerely, Gene Wirchenko |
#6
| |||
| |||
|
|
A simple/simpler solution would be to always sort the values. In other words, to enforce that A is always lower or equal to B, both in the table and whenever you do inserts. That way you don't need two rows for each pair. In the table, this can be enforced with CHECK (a <= b) |
![]() |
| Thread Tools | |
| Display Modes | |
| |