Unique Constraint doesn't appear to be constraining anything - sql-server-2005

I have a Table called Models set up as follows:
ID - PK, Identity
Manufacturer FK - Int32
PriModel FK - Int32
SecModel FK - Int32
FormFactor FK - Int32
Active Char(1)
What I want is Columns 2,3,4,5 to only accept a unique set of values. I ran:
ALTER TABLE dbo.Models ADD CONSTRAINT uc_Models UNIQUE (Manufacturer, PriModel, SecModel, FormFactor)
The command reported completed successfully and I see an index was added, but not a constraint. I am also able to create a duplicate of cols 2-5 with Insert and Update commands. I'm not sure if the issue is the foreign keys or something else altogether.
USE [inventory_v2]
GO
/****** Object: Table [dbo].[Models] Script Date: 4/8/2013 2:01:41 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Models](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Manufacturer] [int] NOT NULL,
[PriModel] [int] NOT NULL,
[SecModel] [int] NOT NULL,
[FormFactor] [int] NOT NULL,
[Active] [char](1) NOT NULL,
CONSTRAINT [PK_Models] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [uc_Models] UNIQUE NONCLUSTERED
(
[Manufacturer] ASC,
[PriModel] ASC,
[SecModel] ASC,
[FormFactor] 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].[Models] WITH CHECK ADD CONSTRAINT [FK_Models_Models_FormFactor] FOREIGN KEY([FormFactor])
REFERENCES [dbo].[Models_FormFactor] ([ID])
GO
ALTER TABLE [dbo].[Models] CHECK CONSTRAINT [FK_Models_Models_FormFactor]
GO
ALTER TABLE [dbo].[Models] WITH CHECK ADD CONSTRAINT [FK_Models_Models_OEMs] FOREIGN KEY([Manufacturer])
REFERENCES [dbo].[Models_OEMs] ([ID])
GO
ALTER TABLE [dbo].[Models] CHECK CONSTRAINT [FK_Models_Models_OEMs]
GO
ALTER TABLE [dbo].[Models] WITH CHECK ADD CONSTRAINT [FK_Models_Models_PriModels] FOREIGN KEY([PriModel])
REFERENCES [dbo].[Models_PriModels] ([ID])
GO
ALTER TABLE [dbo].[Models] CHECK CONSTRAINT [FK_Models_Models_PriModels]
GO
ALTER TABLE [dbo].[Models] WITH CHECK ADD CONSTRAINT [FK_Models_Models_SecModels] FOREIGN KEY([SecModel])
REFERENCES [dbo].[Models_SecModels] ([ID])
GO
ALTER TABLE [dbo].[Models] CHECK CONSTRAINT [FK_Models_Models_SecModels]
GO

Related

How can a join table be part of an ON DELETE CASCADE cycle?

In SQL Server I have a simple database schema, where Authors and Books have a many-many join table, and both have foreign keys to Publishers.
I am not allowed to set ON CASCADE DELETE on all the relations:
Unable to create relationship 'FK_Books_Publishers'.
Introducing FOREIGN KEY constraint 'FK_Books_Publishers' on table 'Books' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
What's the cycle here? Don't cascade cycles end at join tables as they have no foreign keys referencing them?
Or is it that deleting a Publisher may give two causes for deleting a BookAuthor row (via Authors or via Books)? And why would that be a problem?
This is the DDL for the above:
USE [fk-test]
GO
/****** Object: Table [dbo].[Authors] Script Date: 3-6-2022 15:23:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Authors](
[Id] [int] NOT NULL,
[PublisherId] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
CONSTRAINT [PK_Authors] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[BookAuthor] Script Date: 3-6-2022 15:23:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BookAuthor](
[BookId] [int] NOT NULL,
[AuthorId] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Books] Script Date: 3-6-2022 15:23:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Books](
[Id] [int] NOT NULL,
[PublisherId] [int] NOT NULL,
[Title] [nchar](50) NULL,
CONSTRAINT [PK_Books] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Publishers] Script Date: 3-6-2022 15:23:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Publishers](
[Id] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
CONSTRAINT [PK_Publishers] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Authors] WITH CHECK ADD CONSTRAINT [FK_Authors_Authors] FOREIGN KEY([PublisherId])
REFERENCES [dbo].[Publishers] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Authors] CHECK CONSTRAINT [FK_Authors_Authors]
GO
ALTER TABLE [dbo].[BookAuthor] WITH CHECK ADD CONSTRAINT [FK_BookAuthor_Authors] FOREIGN KEY([AuthorId])
REFERENCES [dbo].[Authors] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[BookAuthor] CHECK CONSTRAINT [FK_BookAuthor_Authors]
GO
ALTER TABLE [dbo].[BookAuthor] WITH CHECK ADD CONSTRAINT [FK_BookAuthor_Books] FOREIGN KEY([BookId])
REFERENCES [dbo].[Books] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[BookAuthor] CHECK CONSTRAINT [FK_BookAuthor_Books]
GO
ALTER TABLE [dbo].[Books] WITH CHECK ADD CONSTRAINT [FK_Books_Publishers] FOREIGN KEY([PublisherId])
REFERENCES [dbo].[Publishers] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Books] CHECK CONSTRAINT [FK_Books_Publishers]
GO
It's because there'd be two cascading delete paths from Publisher to BookAuthor,one via Author and one via Books.
A solutions is to modify the two foreign keys
FK_Authors_Authors
FK_Books_Publishers
to
ON DELETE SET NULL
And make PublisherId in Books and Authors nullable.
Then you'll need to do your own custom cascade delete code when deleting a publisher. e.g delete the publisher, then delete the relevant Authors and Books.

Vague error when trying to add a foreign key to an existing table

I need to add a new foreign key to my table called starList. It currently does not have a foreign key relationship with the table called planetList.
So I ran this command:
ALTER TABLE [dbo].[starList] WITH CHECK
ADD CONSTRAINT [FK_starList_planetList]
FOREIGN KEY([planetId]) REFERENCES [dbo].[planetList] ([planetId])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
But I get this error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_starList_planetList".
The conflict occurred in database "astro101", table "dbo.planetList", column 'planetID'.
I am not sure what that means.
I tried looking around my tables on SQL Server but I don't see anything wrong.
Could anyone help me figure out what the error means?
Thanks!
My starList table looks like this:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[starList]
(
[starID] [nvarchar](50) NOT NULL,
[galaxyID] [uniqueidentifier] NOT NULL,
[starTitle] [nvarchar](3000) NULL,
[planetID] [uniqueidentifier] NULL,
CONSTRAINT [PK_StarList]
PRIMARY KEY CLUSTERED ([starID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[starList] WITH CHECK
ADD CONSTRAINT [FK_starList_galaxyList]
FOREIGN KEY([galaxyID]) REFERENCES [dbo].[galaxyList] ([galaxyID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[starList] CHECK CONSTRAINT [FK_starList_galaxyList]
GO
And the planetList table is this:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[planetList]
(
[planetID] [uniqueidentifier] NOT NULL,
[planetText] [nvarchar](max) NULL,
PRIMARY KEY CLUSTERED ([planetID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
You need to check your data in both columns.
There is a value in the column of foreign key table whose associated value doesn't exist in the primary key table.
You have data in starlist.planetid which does not match/correspond to planetlist.planetid.
Both of them need to be the same with values values. It would be better to truncate them and then try creating the contraint.
In short, there is violation of referential integrity rules.
If this is the case, keep in mind to create foreign key before populating the tables.

use two primary keys attribute from a table with different title

I got table "Functions" with Function_ID {PK} and I want another table "Hierarchy" with Hierarchy_ID {PK} which defines tree structure of functions so i need one Function_ID from Function table AS Parent_ID and one Function_ID AS Child. my question is how i can use two primary keys from another table to make it together as Foreign key
I am using SQL Server 2012 and the Management Studio
Many Thanks
Actually you just need to add a ParentFunction_ID column in the Functions table.
You don't need another table if your structure is indeed a tree.
Then make the ParentFunction_ID to be a FK to the same table Functions.
So ParentFunction_ID (FK) would be pointing to Function_ID (PK).
The only record which has ParentFunction_ID NULL would be the root of your tree.
Here is some sample code:
USE [test]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Functions](
[Function_ID] [int] IDENTITY(1,1) NOT NULL,
[FunctionCode] [varchar](max) NULL,
[ParentFunction_ID] [int] NULL,
CONSTRAINT [PK_Functions] PRIMARY KEY CLUSTERED
(
[Function_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].[Functions] WITH CHECK ADD CONSTRAINT [FK_Functions_Functions] FOREIGN KEY([ParentFunction_ID])
REFERENCES [dbo].[Functions] ([Function_ID])
GO
ALTER TABLE [dbo].[Functions] CHECK CONSTRAINT [FK_Functions_Functions]
GO
Name your Functions table a Function table. AFAIK using
plurals for table names is not really a good practice.
So you can do this.
--- 1 ---
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Function](
[Function_ID] [int] IDENTITY(1,1) NOT NULL,
[FunctionCode] [varchar](max) NULL,
CONSTRAINT [PK_Function] PRIMARY KEY CLUSTERED
(
[Function_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
--- 2 ---
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Hierarchy](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ParentFunction_ID] [int] NULL,
[ChildFunction_ID] [int] NULL,
CONSTRAINT [PK_Hierarchy] PRIMARY KEY CLUSTERED
(
[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
ALTER TABLE [dbo].[Hierarchy] WITH CHECK ADD CONSTRAINT [FK_Hierarchy_Function] FOREIGN KEY([ParentFunction_ID])
REFERENCES [dbo].[Function] ([Function_ID])
GO
ALTER TABLE [dbo].[Hierarchy] CHECK CONSTRAINT [FK_Hierarchy_Function]
GO
ALTER TABLE [dbo].[Hierarchy] WITH CHECK ADD CONSTRAINT [FK_Hierarchy_Function1] FOREIGN KEY([ChildFunction_ID])
REFERENCES [dbo].[Function] ([Function_ID])
GO
ALTER TABLE [dbo].[Hierarchy] CHECK CONSTRAINT [FK_Hierarchy_Function1]
GO

1:1 table relation can't insert new row

I have a table inheritance in my database. I have table "Item" and Table "Something". Item has ItemId which is primary key and auto increment. In table Something I have ItemId which is primary key (not autoincrement). Theese tables are in 1:1 relation.
So I have tried to insert data in those tables but this doesn't work:
...
DECLARE #itemId int
INSERT INTO dbo.Items
(ItemTypeId,UserId,CreatedOnDate,Title,Description)
VALUES
(#p_ItemTypeId,#p_UserId,#p_CreatedOnDate,#p_Title,#p_Description)
SELECT #itemId = SCOPE_IDENTITY()
INSERT INTO dbo.Something
(ItemsId)
VALUES
(#itemId)
...
This is the error that I get:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Items_Somethings".
Tables create script:
CREATE TABLE [dbo].[Items](
[ItemdId] [int] IDENTITY(1,1) NOT NULL,
[ItemTypeId] [int] NULL,
[UserId] [int] NULL,
[CreatedOnDate] [smalldatetime] NULL,
[Title] [nvarchar](50) NULL,
[Description] [nvarchar](max) NULL,
CONSTRAINT [PK_Items] PRIMARY KEY CLUSTERED
(
[ItemId] 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
ALTER TABLE [dbo].[Items] WITH CHECK ADD CONSTRAINT [FK_Items_Somethings] FOREIGN KEY([ItemId])
REFERENCES [dbo].[Somethings] ([ItemId])
GO
ALTER TABLE [dbo].[Items] CHECK CONSTRAINT [FK_Items_Somethings]
GO
CREATE TABLE [dbo].[Somethings](
[ItemId] [int] NOT NULL,
CONSTRAINT [PK_Somethings] PRIMARY KEY CLUSTERED
(
[ItemId] 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
ALTER TABLE [dbo].[Items] WITH CHECK ADD CONSTRAINT [FK_Items_Somethings] FOREIGN KEY([ItemId])
REFERENCES [dbo].[Somethings] ([ItemId])
Bad Direction of foreign key.
You should add foreign key to [dbo].[Somethings] and reference [dbo].[Items].ItemId
Like this:
ALTER TABLE [dbo].[Somethings] WITH CHECK ADD CONSTRAINT [FK_Somethings_Items] FOREIGN KEY([ItemId])
REFERENCES [dbo].[Items] ([ItemId])
In this script, you have inverted the inheritance between the tables. If Something table inherits from Item table then the FK has to be created at Table `Something' like this :
ALTER TABLE [dbo].[Somethings] WITH CHECK ADD CONSTRAINT [FK_Somethings_Items] FOREIGN KEY([ItemId])
REFERENCES [dbo].[Items] ([ItemId])
GO
ALTER TABLE [dbo].[Somethings] CHECK CONSTRAINT [FK_Somethings_Items]
GO

The INSERT statement conflicted with the FOREIGN KEY constraint even if its null?

Hi,
I have a table that contains a foreign key value(id). This field is able to be null but the problem is that I get the following exception if I set it to null :
The INSERT statement conflicted with the FOREIGN KEY constraint
Why? it is nullable
Edit1 :
USE [biss]
GO
/****** Object: Table [dbo].[VoucherCodes] Script Date: 10/16/2011 19:55:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[VoucherCodes](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Code] [nvarchar](50) NOT NULL,
[StartDate] [datetime] NOT NULL,
[EndDate] [datetime] NOT NULL,
[InactivatedDate] [datetime] NULL,
[AdCategoryId] [int] NULL,
CONSTRAINT [PK_VoucherCodes] PRIMARY KEY CLUSTERED
(
[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
ALTER TABLE [dbo].[VoucherCodes] WITH CHECK ADD
CONSTRAINT [FK_VoucherCodes_AdCategories] FOREIGN KEY([AdCategoryId])
REFERENCES [dbo].[AdCategories] ([Id])
ON UPDATE SET NULL
GO
ALTER TABLE [dbo].[VoucherCodes] CHECK CONSTRAINT [FK_VoucherCodes_AdCategories]
GO
ALTER TABLE [dbo].[VoucherCodes] WITH CHECK ADD
CONSTRAINT [FK_VoucherCodes_VoucherCodes] FOREIGN KEY([Id])
REFERENCES [dbo].[VoucherCodes] ([Id])
GO
ALTER TABLE [dbo].[VoucherCodes] CHECK CONSTRAINT [FK_VoucherCodes_VoucherCodes]
GO
ALTER TABLE [dbo].[VoucherCodes] WITH CHECK ADD
CONSTRAINT [FK_VoucherCodes_VoucherCodes1] FOREIGN KEY([Id])
REFERENCES [dbo].[VoucherCodes] ([Id])
GO
ALTER TABLE [dbo].[VoucherCodes] CHECK CONSTRAINT [FK_VoucherCodes_VoucherCodes1]
GO
ALTER TABLE [dbo].[VoucherCodes] ADD
CONSTRAINT [DF_VoucherCodes_Inactive] DEFAULT ((1)) FOR [InactivatedDate]
GO
Your foreign key comes from the two self referencing circular FK constraints.
You have the ID columns as FKs of themselves: of course they will fail because they won't exists at INSERT time.
Run this
ALTER TABLE [dbo].[VoucherCodes]
DROP CONSTRAINT FK_VoucherCodes_VoucherCodes, FK_VoucherCodes_VoucherCodes1