Alter table date_time in SQL Server - sql-server

I created a table with the following column:
CREATE TABLE PERFORMANCE
(
...
created DATETIME DEFAULT CURRENT_TIMESTAMP,
....
)
but it has by default the server regional time setting, I'm doing a drop table: to save with the regional configuration of Colombia, but I could not
-- SELECT SWITCHOFFSET(SYSDATETIMEOFFSET(), '-05:00')
ALTER TABLE PERFORMANCE ALTER COLUMN created datetime default SWITCHOFFSET(SYSDATETIMEOFFSET(), '-05:00');

First you should find out the default constraint name by using following
sp_help PERFORMANCE
When you get this then you should drop it and create it using following queries.
Please note that in my case constraint name is DF__PERFORMAN__creat__4C701D42 but it should be different for you
alter table PERFORMANCE drop constraint DF__PERFORMAN__creat__4C701D42
alter table PERFORMANCE add constraint DF__PERFORMAN__creat__4C701D42 default SWITCHOFFSET(SYSDATETIMEOFFSET(), '-05:00') for created
After updating the constraint you can verify it by using SP_help which we have executed first.

Related

Why does "DEFAULT" is causing syntax problem

I'm new in using SQL Server and right now I'm trying to change "Id" column from default ID to GUID.
When using this code
ALTER TABLE dbo.Bookings ALTER COLUMN Id UNIQUEIDENTIFIER DEFAULT NEWID();
It gets me an error
Incorrect syntax near 'DEFAULT'
And I don't understand where is the syntax problem.
Can anyone point it out what is causing this error?
You should use the add constraint syntax:
ALTER TABLE dbo.Bookings ADD CONSTRAINT DF_dbo_Bookings_Id DEFAULT(NEWID()) FOR Id;
Also, if your table have the primary key clustered on that Id column, you could use the NEWSEQUENTIALID for creating unique identifiers that will have less impact on your writes:
ALTER TABLE dbo.Bookings ADD CONSTRAINT DF_dbo_Bookings_Id DEFAULT(NEWSEQUENTIALID()) FOR Id;
Example, on dbfiddle
ALTER TABLE dbo.Bookings
ALTER COLUMN id UNIQUEIDENTIFIER ;
ALTER TABLE dbo.Bookings
ALTER id SET DEFAULT NEWID();
Its possible using the alters separately.
Its the best to backup current table to avoid potential data loss.

Is it possible to insert timestamp in sql?

I want to have a column in which the default timestamp is added when an insertion is done. I have done that in MySQL using choosing default timestamp option. How do I do that in SQL Server?
ALTER TABLE table_name ADD InsertTime DATETIME DEFAULT GETDATE()
ALTER TABLE [table] ADD [CreationTimeStampUTC] DATETIME DEFAULT(GETUTCDATE())
Or you could do the same with GETDATE(), which I think I've seen more in real-world code. Note, of course, that GETDATE() will be valued with the current server time of the SQL Server, and may or may not match up with the current time of the web server if you have one, or particularly the client's machine. Obviously there's no issue with that, just make sure you're aware of the implications ahead of time. You could also store this timestamp as a DATETIMEOFFSET to rid yourself of some of those concerns, but since you're speaking explicitly of on-server default values, I think UTC is perfectly sufficient.
What you're looking for is a default constraint. How you add it depends on whether the column already exists or not. If it doesn't, you can add the column and the constraint in one shot like so:
alter table dbo.yourTable
add [NewColumn] datetime
constraint [DF_NewColumn] default (getdate());
If the column already exists, you can attach a default to it like so:
alter table dbo.yourTable
add constraint [DF_ExistingColumn] default (getdate()) for [ExistingColumn];
Finally, if the table doesn't yet exist, you can add the constraint to the table definition:
create table dbo.yourTable (
NewColumn datetime not null constraint [DF_NewColumn] default (getdate())
)
Note: in all cases, I gave the constraint a name. You can choose not to, but then you'll eventually get a huffy DBA asking why her database comparison is a mess because the constraint names don't match up between dev and prod. :)

TSQL (SQL Server 2005 and 2000) - Changing default and constraint of an existing column?

I am changing the type of a column from bit to tinyint. After that, I want to define the new default value and a new constraint for it. How do I do this? I know how to do it if the column does not exist, but for an existing column my approaches failed so far.
Thanks! :)
Try something like this:
-- change the column type
ALTER TABLE dbo.gradytest
ALTER COLUMN YourColumn TINYINT NULL
-- add a named default constraint
ALTER TABLE dbo.gradytest
ADD CONSTRAINT DF_YourColumn_Default DEFAULT(4) FOR YourColumn

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 to write sql to set alter a column's default value in sql server 2005?

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

Resources