How to remove not null constraint in sql server using query - sql-server

I am trying to remove not null constraint in sql server 2008 without losing data.

ALTER TABLE YourTable ALTER COLUMN YourColumn columnType NULL

Remove constraint not null to null
ALTER TABLE 'test' CHANGE COLUMN 'testColumn' 'testColumn' datatype NULL;

Remove column constraint: not null to null
ALTER TABLE test ALTER COLUMN column_01 DROP NOT NULL;

Reference: https://www.tutorialspoint.com/How-can-we-remove-NOT-NULL-constraint-from-a-column-of-an-existing-MySQL-table
ALTER TABLE tableName MODIFY columnName columnType NULL;

Related

Modifying null column to not null

How to make a NULLABLE column to NOT NULL in SQL SERVER. I made a table with four columns:
My table:
id int null
fname varchar not null
last name not null
contact int null.
Now what i am required is to make id column to be not null.So please help me how we can make a null column to be a not null column.
Use the following statements to do it. Change the name of column id as required
UPDATE [Table] SET id=0 WHERE id IS NULL;
ALTER TABLE [Table] ALTER COLUMN id INTEGER NOT NULL;
Replace [Table] with the name of the table
first Update id Column '0'(Zero) where NULL then right Click on table then select Design and uncheck Allow Nulls checkbox of your Column from sql table design.
ALTER TABLE tableName
ALTER COLUMN columnName nvarchar(200) [NULL|NOT NULL]

Can I change a column from NOT NULL to NULL without dropping it?

Need to alter a table to allow nulls on a column -- but cant drop the column...can I do this? Was trying something like:
ALTER TABLE myTable MODIFY myColumn NULL;
But to no avail....
ALTER TABLE myTable ALTER COLUMN myColumn {DataType} NULL
where {DataType} is the current data type of that column (For example int or varchar(10))
Sure you can.
ALTER TABLE myTable ALTER COLUMN myColumn int NULL
Just substitute int for whatever datatype your column is.
The syntax is very based on database service
SQL Server / MS Access:
ALTER TABLE table_name
ALTER COLUMN column_name datatype NULL;
My SQL / Oracle (prior version 10G):
ALTER TABLE table_name
MODIFY COLUMN column_name datatype NULL;
Oracle 10G and later:
ALTER TABLE table_name
MODIFY column_name datatype NULL;
if you want to set a default value then:
ALTER TABLE table_name
ALTER COLUMN column_name datatype DEFAULT default_value;
For MYSQL
ALTER TABLE myTable MODIFY myColumn {DataType} NULL

How to set a default value for an existing column

This isn't working in SQL Server 2008:
ALTER TABLE Employee ALTER COLUMN CityBorn SET DEFAULT 'SANDNES'
The error is:
Incorrect syntax near the keyword 'SET'.
What am I doing wrong?
This will work in SQL Server:
ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn;
ALTER TABLE Employee ADD DEFAULT 'SANDNES' FOR CityBorn
cannot use alter column for that, use add instead
ALTER TABLE Employee
ADD DEFAULT('SANDNES') FOR CityBorn
The correct way to do this is as follows:
Run the command:
sp_help [table name]
Copy the name of the CONSTRAINT.
Drop the DEFAULT CONSTRAINT:
ALTER TABLE [table name] DROP [NAME OF CONSTRAINT]
Run the command below:
ALTER TABLE [table name] ADD DEFAULT [DEFAULT VALUE] FOR [NAME OF COLUMN]
Hoodaticus's solution was perfect, thank you, but I also needed it to be re-runnable and found this way to check if it had been done...
IF EXISTS(SELECT * FROM information_schema.columns
WHERE table_name='myTable' AND column_name='myColumn'
AND Table_schema='myDBO' AND column_default IS NULL)
BEGIN
ALTER TABLE [myDBO].[myTable] ADD DEFAULT 0 FOR [myColumn] --Hoodaticus
END
There are two scenarios where default value for a column could be changed,
At the time of creating table
Modify existing column for a existing table.
At the time of creating table / creating new column.
Query
create table table_name
(
column_name datatype default 'any default value'
);
Modify existing column for a existing table
In this case my SQL server does not allow to modify existing default constraint value. So to change the default value we need to delete the existing system generated or user generated default constraint. And after that default value can be set for a particular column.
Follow some steps :
List all existing default value constraints for columns.
Execute this system database procedure, it takes table name as a parameter. It returns list of all constrains for all columns within table.
execute [dbo].[sp_helpconstraint] 'table_name'
Drop existing default constraint for a column.
Syntax:
alter table 'table_name' drop constraint 'constraint_name'
Add new default value constraint for that column:
Syntax:
alter table 'table_name' add default 'default_value' for 'column_name'
cheers #!!!
First drop constraints
https://stackoverflow.com/a/49393045/2547164
DECLARE #ConstraintName nvarchar(200)
SELECT #ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
WHERE NAME = N'__ColumnName__'
AND object_id = OBJECT_ID(N'__TableName__'))
IF #ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + #ConstraintName)
Second create default value
ALTER TABLE [table name] ADD DEFAULT [default value] FOR [column name]
ALTER TABLE [dbo].[Employee] ADD DEFAULT ('N') FOR [CityBorn]
in case a restriction already exists with its default name:
-- Drop existing default constraint on Employee.CityBorn
DECLARE #default_name varchar(256);
SELECT #default_name = [name] FROM sys.default_constraints WHERE parent_object_id=OBJECT_ID('Employee') AND COL_NAME(parent_object_id, parent_column_id)='CityBorn';
EXEC('ALTER TABLE Employee DROP CONSTRAINT ' + #default_name);
-- Add default constraint on Employee.CityBorn
ALTER TABLE Employee ADD CONSTRAINT df_employee_1 DEFAULT 'SANDNES' FOR CityBorn;
You can use following syntax, For more information see this question and answers : Add a column with a default value to an existing table in SQL Server
Syntax :
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
WITH VALUES
Example :
ALTER TABLE SomeTable
ADD SomeCol Bit NULL --Or NOT NULL.
CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is
autogenerated.
DEFAULT (0)--Optional Default-Constraint.
WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records.
Another way :
Right click on the table and click on Design,then click on column that you want to set default value.
Then in bottom of page add a default value or binding : something like '1' for string or 1 for int.
Just Found 3 simple steps to alter already existing column that was null before
update orders
set BasicHours=0 where BasicHours is null
alter table orders
add default(0) for BasicHours
alter table orders
alter column CleanBasicHours decimal(7,2) not null
Try following command;
ALTER TABLE Person11
ADD CONSTRAINT col_1_def
DEFAULT 'This is not NULL' FOR Address
ALTER TABLE tblUser
ADD CONSTRAINT DF_User_CreatedON DEFAULT GETDATE() FOR CreatedOn
Like Yuck's answer with a check to allow the script to be ran more than once without error. (less code/custom strings than using information_schema.columns)
IF object_id('DF_SomeName', 'D') IS NULL BEGIN
Print 'Creating Constraint DF_SomeName'
ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn;
END

ALTER TABLE constraint problem

I'm trying to run the following SQL statement:
IF OBJECT_ID('MyTable') IS NOT NULL
DROP TABLE MyTable
SELECT
a.UserId
INTO
MyTable
FROM
UsersTable a
WHERE
a.UserId='12359670-1DC9-4A0A-8AE5-29B664C1A57E'
ALTER TABLE MyTable ALTER COLUMN UserId UNIQUEIDENTIFIER NOT NULL
ALTER TABLE MyTable ADD PRIMARY KEY(UserId)
However, I get the following error:
Cannot define PRIMARY KEY constraint on nullable column in table 'MyTable'.
Any ideas?
This assumes SQL Server based on UNIQUEIDENTIFIER
Put a GO between (or relevant batch separator if not SQL Server)
....
ALTER TABLE MyTable ALTER COLUMN UserId UNIQUEIDENTIFIER NOT NULL
GO
ALTER TABLE MyTable ADD PRIMARY KEY(UserId)
At batch compile time, the column is nullable. So break up the batches.
SQL isn't a line by line procedural language
You'll have to do this in a stored procedure
ALTER TABLE MyTable ALTER COLUMN UserId UNIQUEIDENTIFIER NOT NULL
EXEC('ALTER TABLE MyTable ADD PRIMARY KEY(UserId)')
Found a solution.
I'm using the following statement:
EXEC sp_ExecuteSQL N'ALTER TABLE MyTable ALTER COLUMN UserId UNIQUEIDENTIFIER NOT NULL'
EXEC sp_ExecuteSQL N'ALTER TABLE MyTable ADD PRIMARY KEY(UserId)'
You don't need dynamic SQL. Just create the table and the key first.
CREATE TABLE MyTable (UserId UNIQUEIDENTIFIER NOT NULL PRIMARY KEY);
INSERT INTO MyTable (UserId)
SELECT UserId
FROM UsersTable
WHERE UserId='12359670-1DC9-4A0A-8AE5-29B664C1A57E';

Set a existing column of MS SQL table as NOT NULL

How to Set a existing column of MS SQL table as NOT NULL?
ALTER TABLE tablename
ALTER COLUMN columnname datatype NOT NULL
You will obviously have to make sure that the column does not contain any NULL values before doing this.
E.g.
ALTER TABLE orders
ALTER COLUMN customer_id INT NOT NULL
Firstly ensure that the fields have non null values. In this case I'm working with a field that has a GUID nvarchar so I'll do
UPDATE tablename
SET fieldname = Newid()
WHERE fieldname IS NULL;
Then as Adam Ralph says
ALTER TABLE tablename ALTER COLUMN fieldname datatype NOT NULL

Resources