Syntax needed for adding constraints to fields - sql-server

In Microsoft SQL Server, I want to alter a field to "NOT NULL" AND DEFAULT ''.
I've already issued the following two commands:
ALTER TABLE USR ADD Country Varchar(128)
UPDATE USR SET Country=''
Now I need
1. ALTER TABLE USR ADD CONSTRAINT CountryIsNotNull something
2. ALTER TABLE USR ADD CONSTRAINT CountryDefault default ''

You should be able to google it however here is the syntax:
ALTER TABLE USR
ALTER COLUMN Country varchar(128) NOT NULL
go
ALTER TABLE USR
ADD CONSTRAINT df_usr_conuntry_default DEFAULT '' for Country
go
You could have done the whole thing in one line though with the following:
alter table USR
add Country varchar(128) not null default '' with values

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.

Alter table date_time in 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.

Executing a SQL ALTER TABLE STATEMENT with a variable value

I have added a GUID field into my database tables and I want to update existing users by creating a guid value and then storing this for the related fields but I cant seem to execute the statement when I am using a variable, here is my code:
--Declaration of Script Variables
DECLARE #companyGUID UNIQUEIDENTIFIER
DECLARE #companyDomain NVARCHAR(256)
SET #companyGUID = NEWID()
SET #companyDomain = 'DOMAIN NAME HERE'
--Company Table Update
ALTER TABLE Company ADD GUID UNIQUEIDENTIFIER DEFAULT #companyGUID NOT null
ALTER TABLE Company ADD HasCampaignMonitor BIT
ALTER TABLE Company ADD CampaignMonitorListID NVARCHAR(32)
ALTER TABLE Company ADD CampaignMonitorApiKey NVARCHAR(32)
ALTER TABLE Company ADD CampaignMonitorClientID NVARCHAR(32)
ALTER TABLE Company ADD CampaignMonitorIntegratorID NVARCHAR(16)
ALTER TABLE Company ADD CampaignMonitorRedirectUrl NVARCHAR(256)
UPDATE Company SET GUID = #companyGUID where CompanyID = 1
UPDATE Company SET HasCampaignMonitor = 0 where CompanyID = 1
--User Table Update
ALTER TABLE User ADD GUID UNIQUEIDENTIFIER DEFAULT #companyGUID
ALTER TABLE User ADD DomainStub NVARCHAR(256) DEFAULT #companyDomain
--Activity Progress Table Update
ALTER TABLE ActivityProgress ADD GUID UNIQUEIDENTIFIER DEFAULT #companyGUID
--Answer Table Update
ALTER TABLE Answer ADD GUID UNIQUEIDENTIFIER DEFAULT #companyGUID
You can not use variables in alter statement. The default value is a constraint which can use any static values and some function as the default value.
ALTER TABLE modifies the table's structure and not the stored data.
Alter your tables (possibly with NULL values in the GUID column), Update the new columns, Alter the column with NOT NULL constraint.

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

Tables created by default in user schema

In Sql Server 2008, when I create a table without schema prefix:
create table mytable ( id int identify )
it usually ends up in the schema dbo, with name dbo.mytable.
However, on one of our servers, the tabel ends up belonging to me:
andomar.mytable
Which configuration difference could explain this?
It depends what your default schema is within that database. Even in SQL Server 2005, if your default schema in that one database is andomar, then any tables created without an explicit schema will end up there.
Check the user properties in that database (not the login properties) and see what the default schema is.
If you don't define schema in which you create table it will always use default one.
you can create it like this:
USE DataBaseName -- define database to use
GO
BEGIN TRAN - if you will have any error everything will roll back
CREATE TABLE testovi.razine - schema name is "testovi" and tablename is "razine"
(
id INT NOT NULL IDENTITY(1,1),
razina NVARCHAR(50) NULL,
razinaENG NVARCHAR(50) NULL,
kreirao UNIQUEIDENTIFIER NULL,
VrijemeKreiranja DATETIME NULL
)
ON [PRIMARY]
GO
When you create table always set constraint and index on column most used for transaction
ALTER TABLE testovi.razine ADD CONSTRAINT
PK_mat_razine PRIMARY KEY CLUSTERED
(id) WITH(IGNORE_DUP_KEY=OFF, --check duplicate and don't ignore if try to insert one
STATISTICS_NORECOMPUTE=OFF, -- important for statistic update and query optimization
ALLOW_PAGE_LOCKS=ON) -* I believe that this is default, but always put it to on if not
ON [PRIMARY]
GO
if ##error<>0
BEGIN
ROLBACK TRAN
END
ELSE
BEGIN
COMMIT TRAN --if everything passed o.k. table will be created
END
If you want to set default schema you have to know that it is user based default so you can set it with code:
USE espabiz -- database;
ALTER USER YourUserName WITH DERAULT_SCHEMA = SchemaName; -- SchemaName is default schema for defined user
Ping if you need additional help or mark answer it you find it usable :)

Resources