简体   繁体   中英

Sub-query in tuple constraint DB2

In my database course we use a book (Database System - the Complete Book) which says the following is a valid create table statement in standard SQL:

CREATE TABLE Participants (
    meetid INT NOT NULL,
    -- ...
    CONSTRAINT RoomConstraint
        CHECK (1 >= ALL (SELECT num FROM Numbers)
);

But DB2 complains and gives 20 possible explanations for why this statement fails.

So, does DB2 not support sub-queries in tuple-constraints? And if not, is a TRIGGER the only solution for enforcing the sub-query constraint?

Update: I've found this link which states it ain't possible: http://bytes.com/topic/db2/answers/837390-can-constraint-replace-trigger

But again, is a TRIGGER the only way out? (I'm trying to enforce a relationship where a attribute can refer to two different tables (it ain't my database))

Update 2: It does not work without ALL either:

CREATE TABLE Foo (
   meetid INT NOT NULL,
   CHECK (meetid IN (SELECT meetid FROM Foo)));

Update 3: The idea is that I want a foreign key which references two tables like the following:

Table Participants (pid, ...)
Table Rooms (room, ...)
Table People (userid, ...)

Essentially, a pid shall exists in either Rooms (attribute room) or in People (attribute userid). I could a part of this with a row constraint which checks whether pid is in Rooms or in People - but DB2 won't let me. (I know there is a lot of other stuff to constrain for emulating the foreign key)

How to implement an optional (or alternate) Foreign Key check constraint in SQL Server

create function dbo.meetidinmeetings(@meetid)
returns bit
as
begin
declare @return bit
as
if exists(select 1 from meetings where meetid = @meetid)
set @return =1 
else
set @return = 0
return @return
end

then...

CREATE TABLE Foo (
meetid INT NOT NULL,
ismeeting bit NOT NULL DEFAULT 0

ALTER TABLE FOO
ADD CONSTRAINT CHK_FOO_MEETID
CHECK ((ismeeting = 0) or (ismeeting = 1 and dbo.is_meetidinmeetings(meetid) = 1)))

ALL() is not standard SQL** -- it's a T-SQL extension. DB2 does not support this.

I'm not sure what you are trying to do with your constraint -- it looks like you're trying to ensure that every value of num in the Numbers table is less than or equal to 1. If this is actually the case, you should add a constraint on the Numbers table, not on Participants.

**the SQL92 standard, and I don't believe it was added to SQL99 or SQL2003

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM