1

I am creating a small database and need to create a column in table 1 that will only accept an entry when table 2 value equals to true.

I came up with this code:

ALTER TABLE MarshallGroup
ADD TRANumber NUMERIC(4, 0) CHECK (Member.isMarshall = 'True')

However, I get this error:

The multi-part identifier "Member.isMarshall" could not be bound.

I am aware that I have to use inner join but I don't know where to use it (like I said I am new in SQL).

EDIT: Here are the tables

**First table: Member**     
(PK)TRANumber
firstName
lastName 
gender 
ClubID 
shortNameCatID 
age 
year 
isMarshall <-- this one has to equal to true to be accepted in table 2


**Second Table: MarshallGroup**
(PK)marshallGroupID
(soon to be FK)TRANumber <- this is the column Im creating 
groupNumber 
11
  • @juergend I am using SQL Server Management Studio 2017
    – Gonper
    Dec 30, 2018 at 9:36
  • 1
    You cannot add a check constraint that refers to a different table - you can only check for literal values, or for values in the current table. If you really needs this, you have to handle that validation check in a trigger in SQL Server, or in your application logic
    – marc_s
    Dec 30, 2018 at 9:37
  • There is a way but it is messy IMO: stackoverflow.com/a/2588427/575376
    – juergen d
    Dec 30, 2018 at 9:39
  • @juergend First table: Member (PK)TRANumber firstName lastName gender ClubID shortNameCatID age year isMarshall <-- this one has to equal to true to be accepted in table 2 Second Table: MarshallGroup (PK)marshallGroupID (soon to be FK)TRANumber <- this is the column Im creating groupNumber
    – Gonper
    Dec 30, 2018 at 9:40
  • 1
    Personally I would handle that check in the program logic and not in SQL.
    – juergen d
    Dec 30, 2018 at 10:04

1 Answer 1

0

If I understand correctly, you can do what you want with a foreign key constraint and computed column:

create table Members as (
    . . .,
    TRANumber number(4, 0),
    isMarshall varchar(10),
    . . .
    constraint chk_members_isMarshall check (isMarshall in ('True', 'False')),
    constraint unq_members_TRANumber_isMarshall unique (TRANumber, isMarshall)
);

create table MarshallGroups as (
    . . .,
    isMarshall as ('True') persisted,
    constraint fk_MarshallGroups_Members
        foreign key (TRANumber, isMarshall) references members(TRANumber, isMarshall)
);

The alternatives to this method are either to use a trigger or a user-defined function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.