I’m working with an existing SQL 2005 database that was not implemented with FK relationships between tables. I tried to add the relationships with a database diagram and my application immediately blew up trying to edit or insert any data that is tied to the new FK.
dbo.person [person_id | firstname | lastname | dateofbirth] dbo.campaign [campaign_id | campaign_description] dbo.disposition [disposition_id | disposition_description] dbo.person_campaigns [person_campaign_id | person_id | campaign_id | disposition_id]
The person_campaigns table is where a person, campaign, and disposition are tied together. Can you please provide the appropriate SQL syntax for adding the proper FK relationships between these entities?
EDIT
CREATE TABLE [dbo].[person_campaigns]( [person_campaigns_id] [int] IDENTITY(1,1) NOT NULL, [person_id] [int] NOT NULL, [d_campaign_id] [int] NOT NULL, [d_physician_disposition_id] [int] NULL, CONSTRAINT [PK_person_campaigns] PRIMARY KEY CLUSTERED ( [person_campaigns_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO CREATE TABLE [dbo].[d_campaign]( [d_campaign_id] [int] IDENTITY(1,1) NOT NULL, [name] [varchar](50) NULL, [year] [int] NULL, [isactive] [bit] NOT NULL, CONSTRAINT [PK_d_campaign] PRIMARY KEY CLUSTERED ( [d_campaign_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[d_campaign] ADD CONSTRAINT [DF_d_campaign_isactive] DEFAULT ((1)) FOR [isactive] GO CREATE TABLE [dbo].[d_disposition]( [d_disposition_id] [int] IDENTITY(1,1) NOT NULL, [name] [varchar](50) NULL, [isactive] [bit] NOT NULL, CONSTRAINT [PK_d_disposition] PRIMARY KEY CLUSTERED ( [d_disposition_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[d_disposition] ADD CONSTRAINT [DF_d_disposition_isactive] DEFAULT ((1)) FOR [isactive] GO CREATE TABLE [dbo].[person]( [person_id] [int] IDENTITY(1,1) NOT NULL, [firstname] [varchar](30) NULL, [lastname] [varchar](30) NULL, [dateofbirth] [datetime] NULL CONSTRAINT [PK__person__0BC6C43E] PRIMARY KEY CLUSTERED ( [person_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO
the easiest way to do it is through the database diagram editor; do them one at a time and save the diagram to affect the tables after each connection is made. If it ‘blows up’ it is most likely because the tables contain foreign-key values that do not exist; you’ll have to clean these up first.