1:1 table relation can't insert new row - sql

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

Related

Multiple foreign key constraints to the same primary key

I have two tables:
Image -> ImageId, ImageBinary (Id is int and auto-incremented)
Customer -> Id, CardImageFront, CardImageBack
Where CardImageFront and CardImageBack are Ids referencing to the ImageId column. The customer will take two pictures of their card: one for the front and one for the back. Both of them will be inserted in the Image table with different ImageId. Now I need tried to add two foreign key constraints on the Customer table (one for CardImageFront and another for CardImageBack) referencing the ImageId column, it says:
Introducing FOREIGN KEY constraint on table 'Customer' may cause cycles or multiple cascade paths
Should only a single foreign key constraint is necessary in this case? Will deleting the CardImageFront from Image table will also delete the CardImageBack? Or is there something wrong with the design?
Code for the Image table:
CREATE TABLE [dbo].[Image](
[Id] [int] IDENTITY(1,1) NOT NULL,
[BinaryImage] [varbinary](8000) NOT NULL,
CONSTRAINT [PK_Image] 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
Code for the Customer table:
CREATE TABLE [dbo].[Customer](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](100) NOT NULL,
[ImageFront] [int] NOT NULL,
[ImageBack] [int] NOT NULL,
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
Code for FK constraints:
ALTER TABLE [dbo].[Customer] WITH CHECK ADD CONSTRAINT [FK_1] FOREIGN KEY([ImageFront])
REFERENCES [dbo].[Image] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Customer] WITH CHECK ADD CONSTRAINT [FK_2] FOREIGN KEY([ImageBack])
REFERENCES [dbo].[Image] ([Id])
ON DELETE CASCADE
GO
Error:
Msg 1785, Level 16, State 0, Line 6
Introducing FOREIGN KEY constraint 'FK_2' on table 'Customer' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Msg 1750, Level 16, State 1, Line 6
Could not create constraint or index. See previous errors.

Still FK conflict, even after investigation

4.857 million rows went through the flow OK, and only 38.000 rows sent to error output. This due to a FK conflict. ---> "The INSERT statement conflicted with the FOREIGN KEY constraint "FK_FactTransactions_DimCustomer".
The conflict occurred in database "", table "dbo.DimCustomer", column 'CustomerNr'.".
My problem is, after some investigation, i can't identify any conflict in the primary table dbo.dimcustomer.
Lets take Mid(Named CustomerNr in the DB) "60534658" for an example and let us see.
Picture NR
1: This is a data-view draft of some of the rows that got sent to error output for analysis.
2: This is the table where its supposed to insert, notice that rows with the same CustomerNr already exists, because some rows of the same CustomerNr, for a strange reason, got inserted while others did not
3: And last. This is the actual primary table(Customer table), where the Mid(CustomerNr) reference clearly exists!
Am i missing something here? why is it still in conflict?
ty for any answers!
TABLE STRUCTURE:
CREATE TABLE [dbo].[DimCustomer](
[CustomerNr] [int] NOT NULL,
[CustomerID] [int] NULL,
[GeographyKey] [int] NULL,
[OrgNum] [nvarchar](50) NULL,
[CustomerName] [nvarchar](255) NULL,
[Adress] [nvarchar](255) NULL,
[ZipCode] [nvarchar](255) NULL,
[MCC_Code] [float] NULL,
CONSTRAINT [PK_Dim.Customer_1] PRIMARY KEY CLUSTERED
(
[CustomerNr] 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].[DimCustomer] WITH CHECK ADD CONSTRAINT [FK_DimCustomer_DimGeography] FOREIGN KEY([GeographyKey])
REFERENCES [dbo].[DimGeography] ([GeographyKey])
GO
ALTER TABLE [dbo].[DimCustomer] CHECK CONSTRAINT [FK_DimCustomer_DimGeography]
GO
CREATE TABLE [dbo].[FactTransactions](
[TransactionKey] [int] IDENTITY(1,1) NOT NULL,
[Reportdate] [date] NULL,
[CustomerNr] [int] NULL,
[SchemeID] [smallint] NULL,
[PriceType] [int] NULL,
[Count] [int] NULL,
[Amount] [float] NULL,
[Commission] [float] NULL,
[InterchangeFee] [float] NULL,
[Currency] [nvarchar](3) NULL,
[FeeType] [int] NULL,
CONSTRAINT [PK_FactTransactions] PRIMARY KEY CLUSTERED
(
[TransactionKey] 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].[FactTransactions] WITH CHECK ADD CONSTRAINT [FK_FactTransactions_DimCardScheme] FOREIGN KEY([SchemeID])
REFERENCES [dbo].[DimCardScheme] ([SchemeID])
GO
ALTER TABLE [dbo].[FactTransactions] CHECK CONSTRAINT [FK_FactTransactions_DimCardScheme]
GO
ALTER TABLE [dbo].[FactTransactions] WITH CHECK ADD CONSTRAINT [FK_FactTransactions_DimCustomer] FOREIGN KEY([CustomerNr])
REFERENCES [dbo].[DimCustomer] ([CustomerNr])
GO
ALTER TABLE [dbo].[FactTransactions] CHECK CONSTRAINT [FK_FactTransactions_DimCustomer]
GO
ALTER TABLE [dbo].[FactTransactions] WITH CHECK ADD CONSTRAINT [FK_FactTransactions_DimDate] FOREIGN KEY([Reportdate])
REFERENCES [dbo].[DimDate] ([Date])
GO
ALTER TABLE [dbo].[FactTransactions] CHECK CONSTRAINT [FK_FactTransactions_DimDate]
GO
ALTER TABLE [dbo].[FactTransactions] WITH CHECK ADD CONSTRAINT [FK_FactTransactions_DimPriceType] FOREIGN KEY([PriceType])
REFERENCES [dbo].[DimPriceType] ([PriceType])
GO
ALTER TABLE [dbo].[FactTransactions] CHECK CONSTRAINT [FK_FactTransactions_DimPriceType]
GO
Example error output line:
2015-05-01,60534658,1,1,57,484,5280,3000000000002,78,340000000000003,0,EUR,57,1
Maybe you have some FactTrancsactions pointing to a customer which doesn't exist.
Try this statement to check if there are some transaction pointing to the wrong customer. Each row returned by this statement will bounce if you create the foreign key.
SELECT ft.*
FROM dbo.FactTransactions as ft
LEFT JOIN dbo.DimCustomer as dc
ON ft.CustomerNr = dc.CustomerNr
WHERE dc.CustomerNr IS NULL

Unable to drop foreign key constraint

Table definition:
CREATE TABLE [dbo].[Visualization_ComponentLayouts]
(
[ComponentLayoutId] [int] IDENTITY(1,1) NOT NULL,
[ComponentId] [int] NOT NULL,
[LayoutId] [int] NOT NULL,
[UnitTypeId] [int] NOT NULL,
[ProjectId] [int] NOT NULL,
[CreatedBy] [int] NULL,
[ModifiedBy] [int] NULL,
CONSTRAINT [PK_Visualization_ComponentLayouts] PRIMARY KEY CLUSTERED
(
[ComponentLayoutId] 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].[Visualization_ComponentLayouts] WITH NOCHECK
ADD CONSTRAINT [FK_Visualization_ComponentLayouts_Visualization_ComponentInfo]
FOREIGN KEY([ComponentId])
REFERENCES [dbo].[Visualization_ComponentInfo] ([ComponentId])
GO
ALTER TABLE [dbo].[Visualization_ComponentLayouts] CHECK CONSTRAINT [FK_Visualization_ComponentLayouts_Visualization_ComponentInfo]
GO
ALTER TABLE [dbo].[Visualization_ComponentLayouts] WITH CHECK
ADD CONSTRAINT [FK_Visualization_ComponentLayouts_Visualization_Layouts]
FOREIGN KEY([LayoutId], [ProjectId])
REFERENCES [dbo].[Visualization_Layouts] ([LayoutId], [ProjectId])
GO
ALTER TABLE [dbo].[Visualization_ComponentLayouts] CHECK CONSTRAINT [FK_Visualization_ComponentLayouts_Visualization_Layouts]
GO
Query to drop constraint:
ALTER TABLE Visualization_ComponentLayouts
DROP CONSTRAINT FK_Visualization_ComponentLayouts_Visualization_Layouts
Error I get when I execute above drop query:
'FK_Visualization_ComponentLayouts_Visualization_Layouts' is not a
constraint. Could not drop constraint. See previous errors.
In SQL Server Management Studio, in Object Explorer, when I expand the table node, and within that when I expand constraints node, no constraints are being listed there.
When I execute query : EXEC sp_help 'Visualization_ComponentLayouts'
I get following:
What am I doing wrong?

How to set hierarchic foreign key through another table?

I am not sure if my title really explains the question, so I'll try an example:
Let's say I have:
1) region table: parent regions and subregions in the same table (link A)
2) product table: each product is linked to a single parent region (link B)
3) product_price table: lists the price of a product (C) in all sub regions of that product region (link D >>> the link in question).
(the diagram is showing only the relevant fields, there are a lot more data in region and product)
Is there a way to define the region->region_price key, to include only sub_region_id's of the parent_region in the product->region key??
Or, in the terms of the image, how do I make the D link to include only regions that are children [as in A] of the B & C link?
Hope you are getting my point...
Here are the real tables and links:
CREATE TABLE [dbo].[product](
[product_id] [int] NOT NULL,
[product_name] [nchar](10) NOT NULL,
[parent_region_id] [int] NOT NULL,
CONSTRAINT [PK_product] PRIMARY KEY CLUSTERED
(
[product_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]
CREATE TABLE [dbo].[product_price](
[product_id] [int] NOT NULL,
[sub_region_id] [int] NOT NULL,
[price] [decimal](18, 0) NOT NULL,
CONSTRAINT [PK_product_price] PRIMARY KEY CLUSTERED
(
[product_id] ASC,
[sub_region_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]
CREATE TABLE [dbo].[region](
[region_id] [int] NOT NULL,
[region_name] [nvarchar](50) NOT NULL,
[parent_region_id] [int] NULL,
CONSTRAINT [PK_region] PRIMARY KEY CLUSTERED
(
[region_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]
ALTER TABLE [dbo].[product] WITH CHECK ADD CONSTRAINT [FK_product_region] FOREIGN KEY([parent_region_id])
REFERENCES [dbo].[region] ([region_id])
ALTER TABLE [dbo].[product] CHECK CONSTRAINT [FK_product_region]
ALTER TABLE [dbo].[product_price] WITH CHECK ADD CONSTRAINT [FK_product_price_product] FOREIGN KEY([product_id])
REFERENCES [dbo].[product] ([product_id])
ALTER TABLE [dbo].[product_price] CHECK CONSTRAINT [FK_product_price_product]
ALTER TABLE [dbo].[product_price] WITH CHECK ADD CONSTRAINT [FK_product_price_region] FOREIGN KEY([sub_region_id])
REFERENCES [dbo].[region] ([region_id])
ALTER TABLE [dbo].[product_price] CHECK CONSTRAINT [FK_product_price_region]
ALTER TABLE [dbo].[region] WITH CHECK ADD CONSTRAINT [HK_region_region] FOREIGN KEY([parent_region_id])
REFERENCES [dbo].[region] ([region_id])
ALTER TABLE [dbo].[region] CHECK CONSTRAINT [HK_region_region]
I guess you are trying to enforce a business rule with a database rule, but they're not always the same. Instead, you can run validation querys in your code before inserting or updating, or you could implement a trigger that validates your rules or throws an error.

Unique Constraint doesn't appear to be constraining anything

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