SQL Server UniqueIdentifier as FK - sql-server

I am trying to execute the following but its giving an error of, I tried doing it with designer, same error saying data type, precision and length must be the same, even though they are
ALTER TABLE CustomerUsers
ADD CONSTRAINT fk_CustomerUsers_Users
FOREIGN KEY (CustomerID)
REFERENCES Customers(UniqueID)
Error thrown:
Msg 1769, Level 16, State 1, Line 1
Foreign key 'fk_CustomerUsers_Users' references invalid column 'UniqueID' in referencing table 'CustomerUsers'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
Here is My Table Structure.
CREATE TABLE [dbo].[Customers](
[CustomerID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](500) NOT NULL,
[ContentLocation] [nvarchar](500) NOT NULL,
[UniqueID] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
(
[CustomerID] 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].[CustomerUsers](
[CustomerUserID] [int] IDENTITY(1,1) NOT NULL,
[CustomerUniqueID] [uniqueidentifier] NOT NULL,
[UserID] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_CustomerUsers] PRIMARY KEY CLUSTERED
(
[CustomerUserID] 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].[CustomerUsers] WITH CHECK ADD CONSTRAINT [FK_CustomerUsers_AspNetUsers] FOREIGN KEY([UserID])
REFERENCES [dbo].[AspNetUsers] ([Id])
GO
ALTER TABLE [dbo].[CustomerUsers] CHECK CONSTRAINT [FK_CustomerUsers_AspNetUsers]
GO

There is no column with the name CustomerID in CustomerUsers just CustomerUniqueID
modify your query as below
ALTER TABLE CustomerUsers
ADD CONSTRAINT fk_CustomerUsers_Users
FOREIGN KEY (CustomerUniqueID)
REFERENCES Customers(UniqueID)
Query same as #Drew

I do believe the following should do the trick (in the case that you're wanting to set up CustomerUsers.CustomerUniqueID as a FK)
ALTER TABLE customerusers
ADD CONSTRAINT fk_customerusers_users FOREIGN KEY (customeruniqueid)
REFERENCES customers(uniqueid)
what I changed: inferred that error was related to column not existing, noticed that you had already created a column which looked like what you might have been trying to shoot for, added that

Related

Is there a technical reason why you can't have multiple cascade paths in SQL?

I've been trying to implement a table in TSQL that references another table twice in 2 different columns, and applying cascade UPDATE/DELETE to those references:
CREATE TABLE [dbo].[Discussion](
[id] [bigint] IDENTITY(100000,1) NOT NULL,
[name] [nvarchar](255) NOT NULL,
[originated_user_id] [bigint] NOT NULL,
CONSTRAINT [PK_Discussion] 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
CREATE TABLE [dbo].[User_Badge_Count](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[discussion_id] [bigint] NULL,
[chat_id] [bigint] NULL,
[count] [int] NOT NULL,
CONSTRAINT [PK_User_Badge_Count] 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].[User_Badge_Count] ADD CONSTRAINT [DF_User_Badge_Count_count] DEFAULT ((0)) FOR [count]
GO
ALTER TABLE [dbo].[User_Badge_Count] WITH CHECK ADD CONSTRAINT [FK_User_Badge_Count_Chat] FOREIGN KEY([chat_id])
REFERENCES [dbo].[Discussion] ([id]) ON DELETE CASCADE ON UPDATE CASCADE
GO
ALTER TABLE [dbo].[User_Badge_Count] CHECK CONSTRAINT [FK_User_Badge_Count_Chat]
GO
ALTER TABLE [dbo].[User_Badge_Count] WITH CHECK ADD CONSTRAINT [FK_User_Badge_Count_Discussion] FOREIGN KEY([discussion_id])
REFERENCES [dbo].[Discussion] ([id]) ON DELETE CASCADE ON UPDATE CASCADE
GO
ALTER TABLE [dbo].[User_Badge_Count] CHECK CONSTRAINT [FK_User_Badge_Count_Discussion]
GO
It's done this way because we can consider a discussion to be a "discussion" or a "chat", and we want to reference as such in the badge table. However, trying to create these 2 cascades to the same table results in the TSQL error:
Introducing FOREIGN KEY constraint 'FK_User_Badge_Count_Discussion' on table 'User_Badge_Count' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Is there a technical reason for this restriction? It seems a bit arbitrary; the DBMS could just update/delete the row if either foreign key referenced is updated/deleted?

Cannot create a foreign key becaue it is in conflict with itself

I am trying to add a Foreignkey to a table and i cannot because i get this error:
Msg 547, Level 16, State 0, Line 1 The ALTER TABLE statement
conflicted with the FOREIGN KEY constraint
"FK_RDATA_COMBO_VALUES_ID_REFERENCES". The conflict occurred in
database "MyDatabase", table "dbo.EVA_REFERENCES", column
'ID_REFERENCES'.
The error message says that the problem is a conflict with FK_RDATA_COMBO_VALUES_ID_REFERENCES but this is the name of the FK i am trying to create, it does not exist yet.
This is my table:
CREATE TABLE [dbo].[RDATA_COMBO_VALUES](
[ID_RDATA_COMBO] [int] IDENTITY(1,1) NOT NULL,
[ID_REF_CDATA] [int] NOT NULL,
[ID_MODULE_REC_ID] [int] NOT NULL,
[VALUE] [nvarchar](max) NULL,
[ID_REFERENCES] [int] NOT NULL,
CONSTRAINT [PK_RDATA_COMBO_VALUES] PRIMARY KEY CLUSTERED
(
[ID_RDATA_COMBO] 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].[RDATA_COMBO_VALUES] WITH CHECK ADD CONSTRAINT [FK_RDATA_COMBO_VALUES_ID_REF_CDATA] FOREIGN KEY([ID_REF_CDATA])
REFERENCES [dbo].[EVA_REFERENCE_CDATA] ([ID_REF_CDATA])
GO
ALTER TABLE [dbo].[RDATA_COMBO_VALUES] CHECK CONSTRAINT [FK_RDATA_COMBO_VALUES_ID_REF_CDATA]
GO
And this is the command i use to create the FK:
ALTER TABLE [dbo].[RDATA_COMBO_VALUES] WITH CHECK ADD CONSTRAINT [FK_RDATA_COMBO_VALUES_ID_REFERENCES] FOREIGN KEY([ID_REFERENCES])
REFERENCES [dbo].[EVA_REFERENCES] ([ID_REFERENCES])
Why the ALTER TABLE statements is in conflict with the FK i still not created?
UPDATE:
this question has a continuation in this one that originated allmy questions about this table.
The message could be misleading but the FK i am trying to add is in conflict with the data, because the field contains values that does not exist in the referenced table.
Before creating the FK it is necessary to remove orphans.

How do you deal with foreign keys, unique indexes and default constraints when using a shadow table copy and rename?

I have a large table in a MSSQL 2008 database, to which I need to add a new column, set a value on that new column and then make it not null.
Because the table is large, it keeps timing out on our deployment process. I read that I can use a shadow table and SELECT INTO.., then use sp_rename to replace the original table. As per this answer: https://stackoverflow.com/a/19141346/119624
The table has lots of foreign keys, indexes and constraints. I'm slightly confused as to how I should deal with those.
I assume that the process is as below. But I would appreciate it if someone could confirm whether I'm doing this in the optimum way.
Imagine this is my current table:
CREATE TABLE [dbo].[MyTable](
[MyTableId] [int] IDENTITY(1,1) NOT NULL,
[SomeFkId] [int] NOT NULL,
[IsLocked] [bit] NOT NULL CONSTRAINT [DF_MyTable_IsLocked] DEFAULT ((0)),
CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED
(
[MyTableId] 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].[MyTable] WITH CHECK
ADD CONSTRAINT [FK_MyTable_SomeFk] FOREIGN KEY([SomeFkId])
REFERENCES [dbo].[SomeFk] ([SomeFkId])
GO
ALTER TABLE [dbo].[MyTable] CHECK CONSTRAINT [FK_MyTable_SomeFk]
GO
I now want to add a new shadow table. Do I need to create the table with the defaults and constraints like so?
CREATE TABLE [dbo].[MyTableShadow](
[MyTableId] [int] IDENTITY(1,1) NOT NULL,
[SomeFkId] [int] NOT NULL,
[SomeColumn] [int] NOT NULL,
[IsLocked] [bit] NOT NULL CONSTRAINT [DF_MyTableShadow_IsLocked] DEFAULT ((0)),
[NewColumn] [int] NOT NULL,
CONSTRAINT [PK_MyTableShadow] PRIMARY KEY CLUSTERED
(
[MyTableId] 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].[MyTableShadow] WITH CHECK
ADD CONSTRAINT [FK_MyTableShadow_SomeFk] FOREIGN KEY([SomeFkId])
REFERENCES [dbo].[SomeFk] ([SomeFkId])
GO
ALTER TABLE [dbo].[MyTableShadow] CHECK CONSTRAINT [FK_MyTableShadow_SomeFk]
GO
Then do the SELECT INTO...
SELECT MyTable.*, MyTable.SomeColumn -- copying value
INTO MyTableShandow
FROM MyTable
Then do the rename:
EXEC sp_rename 'MyTable', 'MyTableOld'
EXEC sp_rename 'MyTableShadow', 'MyTable'
Then do the drop:
DROP TABLE MyTableOld
Then rename the constraints and foreign keys:
EXEC sp_rename 'PK_MyTableShadow', 'PK_MyTable', 'object' -- PK
EXEC sp_rename 'FK_MyTableShadow_SomeFk', 'FK_MyTable_SomeFk', 'object' -- FK
EXEC sp_rename 'DF_MyTableShadow_IsLocked', 'DF_MyTable_IsLocked', 'object' -- DF
Is that the correct process, or is there another easier way? (I have a table that has a lot of FKs and constraints, so I'm trying to reduce the pain!

Error while adding foreign key to composite key

I have two table in sql server:
First table Message_Child has a composite primary key (MessageId, ChildId)
Message_Child (MessageId, ChildId, Date)
Second table should contain a foreign key to Message_Child table, so I created two columns: MessageId and ChildId.
Request (RequestId, MessageId, ChildId, type)
And I created the constraint as follow:
Alter table Request
ADD FOREIGN KEY (MessageId, ChildId) REFERENCES Message_Child(MessageId, ChildId);
But I'm getting the following error:
There are no primary or candidate keys in the referenced table 'Message_Child' that match the referencing column list in the foreign key 'FK_Request_534D60F1'.
Edit
Adding the code:
Message_Child table:
CREATE TABLE [dbo].[Message_Child](
[ChildId] [int] NOT NULL,
[MessageId] [int] NOT NULL,
[Date] [datetime] NULL,
CONSTRAINT [PK_Message_Child] PRIMARY KEY CLUSTERED
(
[ChildId] ASC,
[MessageId] 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].[Message_Child] WITH CHECK ADD CONSTRAINT [FK_Message_Child_Child_ChildId] FOREIGN KEY([ChildId])
REFERENCES [dbo].[Child] ([ChildId])
GO
ALTER TABLE [dbo].[Message_Child] CHECK CONSTRAINT [FK_Message_Child_Child_ChildId]
GO
ALTER TABLE [dbo].[Message_Child] WITH CHECK ADD CONSTRAINT [FK_Message_Child_Message_MessageId] FOREIGN KEY([MessageId])
REFERENCES [dbo].[Message] ([MessageId])
GO
ALTER TABLE [dbo].[Message_Child] CHECK CONSTRAINT [FK_Message_Child_Message_MessageId]
GO
RequestQueue table:
CREATE TABLE [dbo].[RequestQueue](
[RequestQueueId] [int] IDENTITY(1,1) NOT NULL,
[PIN] [nvarchar](max) NULL,
[MessageId] [int] NULL,
[ChildId] [int] NULL,
CONSTRAINT [PK_RequestQueue] PRIMARY KEY CLUSTERED
(
[RequestQueueId] 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].[RequestQueue] WITH CHECK ADD CONSTRAINT [FK_RequestQueue_MessageChildId] FOREIGN KEY([RequestQueueId])
REFERENCES [dbo].[RequestQueue] ([RequestQueueId])
GO
ALTER TABLE [dbo].[RequestQueue] CHECK CONSTRAINT [FK_RequestQueue_MessageChildId]
GO
And then I added this:
Alter table [DayCareDB].[dbo].[RequestQueue]
ADD FOREIGN KEY (MessageId, ChildId) REFERENCES [DayCareDB].[dbo].[Message_Child](MessageId, ChildId);
Key order matters here. You need to use (ChildID, MessageID) IN THAT ORDER since that is the key order in your primary key definition.
Alter table [DayCareDB].[dbo].[RequestQueue]
ADD FOREIGN KEY (ChildId, MessageId)
REFERENCES [DayCareDB].[dbo].[Message_Child](ChildId, MessageId);

Composite primary key with foreign key relationships to same table

so I have a table called "Event" and I want to create another table where an Event can contain more Events from the same table. This is what I have so far.
This is the current existing table...
CREATE TABLE [dbo].[EventEvents]
(
[step_id] [uniqueidentifier] NOT NULL PRIMARY KEY,
[title] [nvarchar](200) NOT NULL,
[Enabled] [bit] NOT NULL,
)
Then this is the table I am trying to create...
CREATE TABLE [dbo].[EventEvents]
(
[EventId] [uniqueidentifier] NOT NULL,
[EventChildId] [uniqueidentifier] NOT NULL,
[Enabled] [bit] NOT NULL,
CONSTRAINT [PK_EventEvents] PRIMARY KEY ([EventId], [EventChildId]),
CONSTRAINT [FK_Event_EventChild] FOREIGN KEY ([EventId],[EventChildId]) REFERENCES [dbo].[Event] ([step_id], [step_id])
)
So both EventId and EventChildId both are foreign keys to Event - step_id as 1 event can other events as children within it. But I need both EventId and EventChildId to be composite primary keys.
How can I do this?
At the moment I get an error saying:
Duplicate columns specified in FOREIGN KEY constraint key list
Thanks
I've figured it out, Thanks anyway.
CREATE TABLE [dbo].[EventChildren]
(
[EventId] [uniqueidentifier] NOT NULL,
[EventChildId] [uniqueidentifier] NOT NULL,
[Enabled] [bit] NOT NULL,
CONSTRAINT [EventEvents] PRIMARY KEY CLUSTERED
(
[EventId] ASC,
[EventChildId] 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].[EventChildren] WITH CHECK ADD CONSTRAINT [FK_EventChildren_Event] FOREIGN KEY([EventId])
REFERENCES [dbo].[Event] ([step_id])
GO
ALTER TABLE [dbo].[EventChildren] WITH CHECK ADD CONSTRAINT [FK_EventChildren_EventChild] FOREIGN KEY([EventChildId])
REFERENCES [dbo].[Event] ([step_id])
GO
ALTER TABLE [dbo].[EventChildren] CHECK CONSTRAINT [FK_EventChildren_Event]
GO
ALTER TABLE [dbo].[EventChildren] CHECK CONSTRAINT [FK_EventChildren_EventChild]
GO

Resources