Useally if I want to add default value , I use this way
ALTER TABLE tab1 ADD coll datetime DEFAULT '11-01-15' NOT NULL
however I want to add default value as the getdate().
so If use the below I got the below error
ALTER TABLE tab1 ADD coll datetime DEFAULT GETDATE() NOT NULL
error: ALTER TABLE 'tab1' failed. Default cannot be an expression when adding non-NULL column 'tab1'. Use a default value instead.
what I want is the default value is the getdate(). how to do that when adding a new datetime column ?
I solved my question by adding the column to null
alter table tab1 add col1 datetime default getdate() null
then I modify it to not null
Use the below for Sybase :
ALTER TABLE table_name
ADD effective_date Datetime DEFAULT "3/16/2009 09:15" NOT NULL
ALTER TABLE table_name
REPLACE effective_date DEFAULT getdate()
Related
Currently I have a column named CreatedDate in a Shipper table I created. It is nullable. My task is to change the created date to be a required field, not allow nulls, and have a default of GetDate(). This has to be done in a single query... Keep in mind there is no data in my table yet. I've tried the following code and I can't seem to get it to work. This is a homework assignment and I'm only looking for guidance. Any help would be greatly appreciated. Thanks in advance.
USE Business
ALTER TABLE Shipper
ALTER COLUMN CreatedDate date NOT NULL
CONSTRAINT CNDefaultCreatedDate
DEFAULT GETDATE() For CreatedDate;
Two different statements, I assume this is SQL Server:
--Add the default
ALTER TABLE [Shipper] --What table
ADD CONSTRAINT [def_createddate] --Give the constraint a name
DEFAULT GETDATE() FOR [CreatedDate]; --default of what for which column
--Set to not allow NULL
ALTER TABLE [Shipper] --What table
ALTER COLUMN [CreatedDate] DATE NOT NULL; --altering what column and either NULL or NOT NULL
Understand adding a default will not update existing data. I know you mentioned your table does not have data, but in the future the null values must be updated to some value before the ALTER COLUMN NOT NULL is allowed.
Here's reference to the MS documentation ALTER TABLE
If the column did not already exist you can add it, set it not null and then even update existing rows in one statement:
--If Shipper did not already have the column CreatedDate
ALTER TABLE [Shipper]
ADD [CreatedDate] DATE NOT NULL
CONSTRAINT [def_createddate] DEFAULT GETDATE()
WITH VALUE --if column is nullable use this and it will update existing records with the default. It column is NOT NULL this is applied by default.
Have you tried this:
USE Business
ALTER TABLE Shipper
ALTER COLUMN CreatedDate date NOT NULL DEFAULT GETDATE();
I have table with 100 rows and I am adding new column with default value as show below.
ALTER TABLE AccountDetails
ADD
UpdatedOn DATETIME DEFAULT GETDATE(),
UpdatedBy VARCHAR(50) DEFAULT 'System'
After execution of this alter statement new columns will be added to table ... which is perfect! however values for the existing rows for these columns will NULL.
Is there anyways where it will have default value by default instead of the executing separate update statement for those column to update default value explicitly?
I got the answer myself. If we put NOT NULL constraint as well in alter statement so while altering table to add new column, default value will be applied to new column and not null constraint will not be violated.
ALTER TABLE AccountDetails
ADD
UpdatedOn DATETIME NOT NULL DEFAULT GETDATE(),
UpdatedBy VARCHAR(50) NOT NULL DEFAULT 'System'
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
[WITH VALUES]
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
I've got a table that collects forms submitted from our website, but for some reason, when they created the table, they didn't put a timestamp in the table. I want it to enter the exact date and time that the record was entered.
I know it's in there somewhere, but I can't seem to find how to set the default value (like in Access, you use getNow() or Now()) but I don't know where to put it.
For modifying an existing column in an existing table:
ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn
This can also be done through the SSMS GUI.
Put your table in design view (Right click on table in object explorer->Design)
Add a column to the table (or click on the column you want to update if it already exists)
In Column Properties, enter (getdate()) in Default Value or
Binding field as pictured below
In that table in SQL Server, specify the default value of that column to be CURRENT_TIMESTAMP.
The datatype of that column may be datetime or datetime2.
e.g.
Create Table Student
(
Name varchar(50),
DateOfAddmission datetime default CURRENT_TIMESTAMP
);
While the marked answer is correct with:
ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn
You should always be aware of timezones when adding default datetime values in to a column.
Say for example, this datetime value is designed to indicate when a member joined a website and you want it to be displayed back to the user, GETDATE() will give you the server time so could show discrepancies if the user is in a different locale to the server.
If you expect to deal with international users, it is better in some cases to use GETUTCDATE(), which:
Returns the current database system timestamp as a datetime value. The database time zone offset is not included. This value represents the current UTC time (Coordinated Universal Time). This value is derived from the operating system of the computer on which the instance of SQL Server is running.
ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETUTCDATE() FOR YourColumn
When retrieving the values, the front end application/website should transform this value from UTC time to the locale/culture of the user requesting it.
Disallow Nulls on the column and set a default on the column of getdate()
/*Deal with any existing NULLs*/
UPDATE YourTable SET created_date=GETDATE() /*Or some sentinel value
'19000101' maybe?*/
WHERE created_date IS NULL
/*Disallow NULLs*/
ALTER TABLE YourTable ALTER COLUMN created_date DATE NOT NULL
/*Add default constraint*/
ALTER TABLE YourTable ADD CONSTRAINT
DF_YourTable_created_date DEFAULT GETDATE() FOR created_date
The syntax for this when creating a new table is:
CREATE TABLE MyTable
(
MYTableID INT IDENTITY(1,1),
CreateDate DATETIME NOT NULL CONSTRAINT DF_MyTable_CreateDate_GETDATE DEFAULT GETDATE()
)
This works for me...
ALTER TABLE [accounts]
ADD [user_registered] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ;
This also works:
CREATE TABLE Example(
...
created datetime default GETDATE()
);
Or:
ALTER TABLE EXAMPLE ADD created datetime default GETDATE();
This worked for me. I am using SQL Developer with Oracle DB:
ALTER TABLE YOUR_TABLE
ADD Date_Created TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL;
Let's say you create a database table for a registration system.
IF OBJECT_ID('dbo.registration_demo', 'U') IS NOT NULL
DROP TABLE dbo.registration_demo;
CREATE TABLE dbo.registration_demo (
id INT IDENTITY PRIMARY KEY,
name NVARCHAR(8)
);
Now a couple people register.
INSERT INTO dbo.registration_demo (name) VALUES
('John'),('Jane'),('Jeff');
Then you realize you need a timestamp for when they registered.
If this app is limited to a geographically localized region, then you can use the local server time with GETDATE(). Otherwise you should heed Tanner's consideration for the global audience with GETUTCDATE() for the default value.
Add the column with a default value in one statement like this answer.
ALTER TABLE dbo.registration_demo
ADD time_registered DATETIME DEFAULT GETUTCDATE();
Let's get another registrant and see what the data looks like.
INSERT INTO dbo.registration_demo (name) VALUES
('Julia');
SELECT * FROM dbo.registration_demo;
id name time_registered
1 John NULL
2 Jane NULL
3 Jeff NULL
4 Julia 2016-06-21 14:32:57.767
To make it simpler to follow, I will summarize the above answers:
Let`s say the table is called Customer
it has 4 columns/less or more...
you want to add a new column to the table where every time when there is insert... then that column keeps a record of the time the event happened.
Solution:
add a new column, let`s say timepurchase is the new column, to the table with data type datetime.
Then run the following alter:
ALTER TABLE Customer ADD CONSTRAINT DF_Customer DEFAULT GETDATE() FOR timePurchase
In SQLPlus while creating a table it is be like as
SQL> create table Test
( Test_ID number not null,
Test_Date date default sysdate not null );
SQL> insert into Test(id) values (1);
Test_ID Test_Date
1 08-MAR-19
I have a table [Product] with a column [CreateTime] datetime null, and is has some data already.
How can I set the column [CreateTime] 's default value to getdate(), and make the new added data to have a default value getdate() for column [CreateTime].
You cannot change a default - you will need to first drop it, and then recreate it.
In order to drop it, you need to know its name, and then use
ALTER TABLE dbo.Product
DROP CONSTRAINT yourOldDefaultConstraint
Once you've done that, you can add a new default constraint, and in order to apply it to existing rows, use the "WITH VALUES" part:
ALTER TABLE dbo.Product
ADD CONSTRAINT NewDefaultConstraintName
DEFAULT GetDate() FOR CreateTime WITH VALUES
Oops - sorry, the "WITH VALUES" only seems to work if you create a DEFAULT constraint at the time you create the table, or if you add the column - it doesn't seem to get applied to an existing column.
In this case you would just have to follow your ALTER TABLE statement with something like this:
UPDATE dbo.T_Product
SET CreateTime = GETDATE()
WHERE CreateTime IS NULL
That should do the trick, too!
Marc