When the primary key table is updated, an error may occur if it is referenced by a dependent table. This error indicates that the update statement conflicted with the dependency between the two tables. To overcome this error, you can either update the dependent table or delete the row from the primary key table.
Foreign Key Constraints in SQL
STEP 1:
USE [YourDatabase]
GO
STEP 2:
ALTER TABLE [dbo].[YourForeignKeyTable] DROP CONSTRAINT [FK_YourForeignKeyTable_YourPrimaryKeyTable]
GO
STEP 3:
DROP TABLE [dbo].[YourPrimaryKeyTable]
GO
STEP 4:
CREATE TABLE [dbo].[YourPrimaryKeyTable](
[YourPrimaryKeyTableId] [uniqueidentifier] NOT NULL,
[YourPrimaryKeyTableName] [nvarchar](100) NULL,
CONSTRAINT [PK_YourPrimaryKeyTable] PRIMARY KEY CLUSTERED
(
[YourPrimaryKeyTableId] ASC
)
) ON [PRIMARY]
GO
STEP 5:
INSERT [dbo].[YourPrimaryKeyTable] ([YourPrimaryKeyTableId], [YourPrimaryKeyTableName]) VALUES (N'c7954f89-b5f0-47b7-962f-0c5b2800cff2', N'Civil')
GO
INSERT [dbo].[YourPrimaryKeyTable] ([YourPrimaryKeyTableId], [YourPrimaryKeyTableName]) VALUES (N'c7954f89-b5f0-47b7-962f-0c5b2800cff3', N'Mechanical')
GO
STEP 6:
ALTER TABLE [dbo].[YourForeignKeyTable] WITH CHECK ADD CONSTRAINT [FK_YourForeignKeyTable_YourPrimaryKeyTable]
FOREIGN KEY([YourForeignKeyTableId]) REFERENCES [dbo].[YourPrimaryKeyTable] ([YourPrimaryKeyTableId])
GO
Code language: JavaScript (javascript)
And now you are done. You can also easily handle errors for MS SQL Server Transact-SQL with a simple mechanism. You can also check out the basic introduction to SQL Queries from this link to have a comprehensive outlook on the full topic.
Add a Comment