I have a table:
MyTable{
Id int not null;
Name varchar not null;
TypeId int null;
}
Now i want to make my TypeId
column is not null
.
First fill it with data:
update [dbo].[MyTable]
set [dbo].[MyTable].[TypeId] = 1
where [dbo].[MyTable].[TypeId] is null
And set not null:
go
ALTER TABLE [dbo].[MyTable] ALTER COLUMN [TypeId] BIT NOT NULL;
But get an error:
Msg 5074, Level 16, State 1, Line 1
The object 'FK_MyTable_ObjTypes' is dependent on column 'TypeId'.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE ALTER COLUMN TypeId failed because one or more objects access this column.
What to do in this case? I cant use after table if column is FK?
I tried disable constreints:
GO
ALTER TABLE [dbo].[MyTable] NOCHECK CONSTRAINT [FK_MyTable_ObjTypes];
go
ALTER TABLE [dbo].[MyTable] ALTER COLUMN [TypeId] BIT NOT NULL;
GO
ALTER TABLE [dbo].[MyTable] CHECK CONSTRAINT [FK_MyTable_ObjTypes];
But get same error.
Drop and recreate constrains help me. This is my query:
GO
ALTER TABLE [dbo].[MyTable] DROP CONSTRAINT [FK_MyTable_ObjTypes];
go
ALTER TABLE [dbo].[MyTable] ALTER COLUMN [TypeId] INT NOT NULL;
GO
ALTER TABLE [dbo].[MyTable] WITH NOCHECK
ADD CONSTRAINT [FK_MyTable_ObjTypes] FOREIGN KEY ([TypeId]) REFERENCES [dbo].[ObjTypes] ([Id]);
GO
ALTER TABLE [dbo].[MyTable] WITH CHECK CHECK CONSTRAINT [FK_MyTable_ObjTypes];