How to set column NOT NULL? - sql

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];

Your Foreign Key FK_MyTable_ObjTypes references the TypeId column, so changing the column would invalidate the constraints of the FK.
You will need to remove the FK first (script it as a CREATE so you can see what the existing definition is). Then ALTER your column, before recreating the FK using the newly modified column.

Yo can disable the FK 'FK_MyTable_ObjTypes', alter the column and enable again the FK:
How can foreign key constraints be temporarily disabled using T-SQL?

Related

Change column to foreign key

How do I change an existing column from bit to a foreign key (int)?
For example, column NEW_B was created like this:
ALTER TABLE [dbo].[APPLICATION]
ADD [NEW_B] [bit] NULL
GO
But now I want the NEW_B to reference column ID (int) of table ATTACHMENT (want to keep the name NEW_B, also allow NULLs).
Here is the syntax:
--alter existing column to int
ALTER TABLE [dbo].[APPLICATION] ALTER COLUMN [NEW_B] INT NULL
GO
--add foreign key constraint
ALTER TABLE [dbo].[APPLICATION] WITH CHECK ADD CONSTRAINT [FK_APPLICATION_ATTACHMENT] FOREIGN KEY([NEW_B])
REFERENCES [dbo].[ATTACHMENT] ([ID])
GO
ALTER TABLE [dbo].[APPLICATION] CHECK CONSTRAINT [FK_APPLICATION_ATTACHMENT]
GO

How to change the column length of a primary key in SQL Server?

I know how to change the length of a column, but my SQL statement fails because the column I'm trying to change is a PK, so I get the following error:
Msg 5074, Level 16, State 1, Line 1
The object 'PK_TableName' is dependent on column 'PersonID'.
PersonID = PK.
I've read What is the sql to change the field length of a table column in sql server which only applies to non-PK columns.
I tried this:
ALTER TABLE table_name
ALTER COLUMN column_name <new datatype>
See below sample example how to increase size of the primary column
Create a sample table
create table abc (id varchar(10) primary key)
Find primary constraint in key constraints tables
select object_name(object_id),* from sys.key_constraints where object_name(parent_object_id) = 'abc
Drop constraint
ALTER TABLE abc
DROP CONSTRAINT PK__abc__3213E83F74EAC69B
(Replace PK__abc__3213E83F74EAC69B with constraint name you receive.)
Add not null
ALTER TABLE abc alter column id varchar(20) NOT NULL;
Add primary key again
ALTER TABLE abc
ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (id)
ALTER TABLE <Table_Name>
DROP CONSTRAINT <constraint_name>
ALTER TABLE table_name
ALTER COLUMN column_name datatype
ALTER TABLE <Table_Name>
ADD CONSTRAINT <constraint_name> PRIMARY KEY (<Column1>,<Column2>)
SQLServer 2008 did not allow me to change a primary key with data so I deactivated all the constraints, performed the command and activated all the constraints again. The commands are:
EXEC sp_MSforeachtable #command1="ALTER TABLE ? NOCHECK CONSTRAINT ALL"
-- commands here
EXEC sp_MSforeachtable #command1="ALTER TABLE ? CHECK CONSTRAINT ALL"

How to Write a Script to add extra columns for my primary key

I have the following table in SQL Server 2008 R2
Now I need to write a script to add a new column cusomerVLANID as part of the primary key, so that the three columns becomes the primary key, is there a way to write such script.
Second thing I want to write a script to remove the Allow Null, check box from the CustomerVLANID columns ?
Thanks
ALTER TABLE <Table_Name>
DROP CONSTRAINT <constraint_name>
ALTER TABLE <Table_Name>
ADD CONSTRAINT <constraint_name> PRIMARY KEY ([ID], [CustomerName], [CustomerVLANSID])
Run this statement separately to set up the NOT NULL constraint:
ALTER TABLE <Table_Name>
ALTER COLUMN [CustomerVLANSID] INT NOT NULL
alter table TABLE1
alter column [CustomerVLANID] int not null
I hope this helps,
-Thomas
RosSQL.blogspot.com

Alter Table Add Column with Default value And FK, that Value no existing in FK Reference Data

This is My Tables :
Member : Id, ....
Product: Id, ....
My Member Table have some values none if them with Id = 0 and I don't want to add any member with Id = 0, So I try to run this Script:
ALTER TABLE [Product]
ADD [Member_Id] BIGINT NOT NULL DEFAULT(0),
CONSTRAINT [FK_Product_Member] FOREIGN KEY ([Member_Id]) REFERENCES [Member];
So There is an Error :
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Product_Member".
So I try this one:
SET IDENTITY_INSERT [Member] ON
INSERT INTO [Member] ([Id]) VALUES (0);
SET IDENTITY_INSERT [Member] OFF
ALTER TABLE [Product]
ADD [Member_Id] BIGINT NOT NULL DEFAULT(0),
CONSTRAINT [FK_Product_Member] FOREIGN KEY ([Member_Id]) REFERENCES [Member];
DELETE FROM [Member] WHERE [Member].[Id] = 0;
Then The new Error is:
The DELETE statement conflicted with the REFERENCE constraint "FK_Product_Member".
If I try to create all Tables again, every thing will be OK of course with lost my Data so need to get backup, create tables and restore data. So Is there any way to alter Table with this situation? what is your suggestion?
The only "value" that you can have in a referencing table, such that the foreign key constraint is not enforced, is NULL. Not 0, or any other magic value.
So the obvious solution is to allow NULLs:
ALTER TABLE [Product]
ADD [Member_Id] BIGINT NULL,
CONSTRAINT [FK_Product_Member] FOREIGN KEY ([Member_Id]) REFERENCES [Member];
your "alter table" is the better way to do this.but at first you are adding the table with value "0" and this is "FOREIGN KEY" but you have not a Member with value "0" so you get error.
the best way as a know is .alter table and then make the true value to the new column and then alter the column and set that to the "FOREIGN KEY"

The ALTER TABLE statement conflicted with the FOREIGN KEY constrain

I'm kind of new to scripting in SQL and I have encountered an error in one of my scripts.
The problematic section is:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE dbo.WorkspaceSettings
(
Id INT NOT NULL IDENTITY PRIMARY KEY ,
ReportColorRGB1 VARCHAR(15) NOT NULL DEFAULT '61,105,138' ,
ReportColorRGB2 VARCHAR(15) NOT NULL DEFAULT '180,210,121'
)
GO
ALTER TABLE Workspace ADD WorkspaceSettingsId int NOT NULL default 1;
GO
ALTER TABLE Workspace
ADD CONSTRAINT FK_WorkspaceSettings_Workspace
FOREIGN KEY (WorkspaceSettingsId)
REFERENCES WorkspaceSettings(Id);
GO
And receive the following error message:
Msg 547, Level 16, State 0, Line 1
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_WorkspaceSettings_Workspace". The conflict occurred in database "ClearRisk2_0", table "dbo.WorkspaceSettings", column 'Id'.
Can someone please tell me where I'm going wrong?
The default value of 1 that you've specified for the Workspace.WorkspaceSettingsId column does not yet exist in your WorkspaceSettings table, hence the FK violation.
Just add the following phrase after ALter table sattement:
with nocheck
So, it will be:
Use Database_name
Go
ALTER TABLE ResultScan with nocheck
ADD CONSTRAINT FK_ResultScan_ListVM FOREIGN KEY (TypeAnVirus)
REFERENCES ListVM (Id)
ON DELETE CASCADE
ON UPDATE CASCADE
;
GO