How do I remove a DEFAULT constraint? - sql-server

This is what I tried. I simply want to remove the constraint I just did there
ALTER TABLE product
ADD DEFAULT NULL FOR sale_id
ALTER TABLE product
ALTER COLUMN sale_id DROP DEFAULT

ALTER TABLE TABLE_NAME
DROP CONSTRAINT <constraint_name>
Eg:
ALTER TABLE students
ALTER COLUMN ph
DROP NOT NULL;

Related

How can I insert the first 8 characters of a GUID into a colum when a new row is created?

I have a SQL server table in my database.
There is a column named Code in a table called Admin.
How can I make this default to the first 8 characters of a GUID? Note that this column is a varchar(8).
While Alter table
ALTER TABLE ADMIN
ADD CONSTRAINT DF_SomeName DEFAULT LEFT(NEWID(), 8) FOR Code;
OR
ALTER TABLE ADMIN
ADD CONSTRAINT DF_SomeName DEFAULT RIGHT(NEWID(), 8) FOR Code;
OR
ALTER TABLE ADMIN
ADD CONSTRAINT DF_SomeName DEFAULT SUBSTRING(CAST(NEWID() as VARCHAR(50)),1,8 ) FOR Code;
While Creating Table
CREATE TABLE ADMIN(
Code varchar(8)
CONSTRAINT DF_PurchaseOrderDetail_rowguid DEFAULT
LEFT(NEWID(), 8) FOR Code
)
OR
CREATE TABLE ADMIN(
Code varchar(8)
CONSTRAINT DF_PurchaseOrderDetail_rowguid DEFAULT
RIGHT(NEWID(), 8) FOR Code
)
OR
CREATE TABLE ADMIN(
Code varchar(8)
CONSTRAINT DF_PurchaseOrderDetail_rowguid DEFAULT
SUBSTRING(CAST(NEWID() as VARCHAR(50)),1,8 ) FOR Code
)
ALTER TABLE [dbo].[table]
ADD CONSTRAINT [DF_table_myColumn] DEFAULT(left(newid(), (8)))
FOR [myColumn]
GO
Add a default constraint:
ALTER TABLE [dbo].[Admin] ADD CONSTRAINT [DF_Admin_Code]
DEFAULT (substring(CONVERT([varchar](50),newid(),0),(1),(8))) FOR [Code]

Alter column Datatype

I have a table dbo.ExceptionMessage and now I want to change the column datatype nvarchar(100) to nvarchar(MAX). I used alter query for changing this
ALTER TABLE dbo.ExceptionMessage ALTER COLUMN Address nvarchar(MAX)
and while excecuting this query it shows some error like.
The object 'DF_ExceptionMessage_Address' is dependent on column 'Address'.
ALTER TABLE ALTER COLUMN Address failed because one or more objects access this column.
How can we solve this...
First Delete all Constraint Like this
ALTER TABLE TableName DROP CONSTRAINT [DF__TableName__ColumnName__FieldName]
and then perform change
ALTER TABLE dbo.ExceptionMessage ALTER COLUMN Address nvarchar(MAX)
then re enter the constraints
You have to find out which type of constraint DF_ExceptionMessage_Address is, drop it, alter the column type and then re-create the constraint if you need it.
you try first:
ALTER TABLE <tablename> DROP CONSTRAINT <Con_Name>;
And Then Do your Alter
ALTER TABLE dbo.ExceptionMessage ALTER COLUMN Address nvarchar(MAX)
Again Add Constraint
thiz help you to alter
alter table TableName
alter column ColumnName nvarchar(200);

Cannot drop FK Constraint

I keep getting the error when running the code below:
Cannot truncate table 'Entry' because it is being referenced by a FOREIGN KEY constraint.
--ALTER TABLE [dbo].[Entry] DROP CONSTRAINT [PK_Entry_Id]
ALTER TABLE [dbo].[Entry] DROP CONSTRAINT [DF_Entry_HideChrome]
ALTER TABLE [dbo].[Entry] DROP CONSTRAINT [DF_Entry_IsDiscussionEnabled]
ALTER TABLE [dbo].[Entry] DROP CONSTRAINT [DF_Entry_MetaDescription]
ALTER TABLE [dbo].[Entry] DROP CONSTRAINT [DF_Entry_MetaTitle]
Truncate table [Entry]
ALTER TABLE [dbo].[Entry] ADD CONSTRAINT [DF_Entry_HideChrome] DEFAULT ((0)) FOR [HideChrome]
GO
ALTER TABLE [dbo].[Entry] ADD CONSTRAINT [DF_Entry_IsDiscussionEnabled] DEFAULT ((1)) FOR [IsDiscussionEnabled]
GO
ALTER TABLE [dbo].[Entry] ADD CONSTRAINT [DF_Entry_MetaDescription] DEFAULT ('') FOR [MetaDescription]
GO
ALTER TABLE [dbo].[Entry] ADD CONSTRAINT [DF_Entry_MetaTitle] DEFAULT ('') FOR [MetaTitle]
GO
ALTER TABLE [dbo].[Entry] ADD CONSTRAINT [DF_EntryStatus] DEFAULT ('Public-Page') FOR [Status]
GO
Ok so I dropped all other constraints from any tables referencing this table but I still get one more error saying there's still a PK constraint referencing my Entry table.
I go and check out the dependencies on Entry (view dependencies) and see that the comment table is still dependent on it:
Then I see there's a FK as one of the main fields of the comment table but you can't drop that I guess.
So I don't see what other dependencies are referencing this Entry table when View Dependencies says the only table left after I dropped constraints on the other tables is from the Comment table? I don't see it.
In the code of dropping the constraint that you have provide you are not dropping the DF_EntryStatus key. You have only dropped these 4 keys.
ALTER TABLE [dbo].[Entry] DROP CONSTRAINT [DF_Entry_HideChrome]
ALTER TABLE [dbo].[Entry] DROP CONSTRAINT [DF_Entry_IsDiscussionEnabled]
ALTER TABLE [dbo].[Entry] DROP CONSTRAINT [DF_Entry_MetaDescription]
ALTER TABLE [dbo].[Entry] DROP CONSTRAINT [DF_Entry_MetaTitle]
As this DF_EntryStatus still referencing you are not able to truncate the table.
Hope this solves our problem.
For some odd reason, I had to drop the key FK_Comment_Comment. Don't know how it's related to the Entry table though...weird.

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

How do I drop a foreign key in SQL Server?

I have created a foreign key (in SQL Server) by:
alter table company add CountryID varchar(3);
alter table company add constraint Company_CountryID_FK foreign key(CountryID)
references Country;
I then run this query:
alter table company drop column CountryID;
and I get this error:
Msg 5074, Level 16, State 4, Line 2
The object 'Company_CountryID_FK' is dependent on column 'CountryID'.
Msg 4922, Level 16, State 9, Line 2
ALTER TABLE DROP COLUMN CountryID failed because one or more objects access this column
I have tried this, yet it does not seem to work:
alter table company drop foreign key Company_CountryID_FK;
alter table company drop column CountryID;
What do I need to do to drop the CountryID column?
Thanks.
Try
alter table company drop constraint Company_CountryID_FK
alter table company drop column CountryID
This will work:
ALTER TABLE [dbo].[company] DROP CONSTRAINT [Company_CountryID_FK]
I think this will helpful to you...
DECLARE #ConstraintName nvarchar(200)
SELECT
#ConstraintName = KCU.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU
ON KCU.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
AND KCU.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
AND KCU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
WHERE
KCU.TABLE_NAME = 'TABLE_NAME' AND
KCU.COLUMN_NAME = 'TABLE_COLUMN_NAME'
IF #ConstraintName IS NOT NULL EXEC('alter table TABLE_NAME drop CONSTRAINT ' + #ConstraintName)
It will delete foreign Key Constraint based on specific table and column.
First check of existence of the constraint then drop it.
if exists (select 1 from sys.objects where name = 'Company_CountryID_FK' and type='F')
begin
alter table company drop constraint Company_CountryID_FK
end
alter table company drop constraint Company_CountryID_FK
I don't know MSSQL but would it not be:
alter table company drop **constraint** Company_CountryID_FK;
You can also Right Click on the table, choose modify, then go to the attribute, right click on it, and choose drop primary key.
Are you trying to drop the FK constraint or the column itself?
To drop the constraint:
alter table company drop constraint Company_CountryID_FK
You won't be able to drop the column until you drop the constraint.

Resources