How do I alter table to add defaults? - sql

I'd like to modify a table that already has data in the database to have a column reflect default data when it is populated.
Specifically, I'd like to take two columns:
[Created] [datetime] NULL ,
[CreatedBy] [varchar](50) NULL ,
And change them to have defaults like the following:
[Created] [datetime] NULL DEFAULT GETDATE(),
[CreatedBy] [varchar](50) NULL DEFAULT USER_ID(),
Can something like this be accomplished with an alter table statement? I'm using Azure so I can't edit the tables in the GUI.

ALTER TABLE dbo.TableName
ADD CONSTRAINT df_Created DEFAULT (GETDATE()) FOR Created;
ALTER TABLE dbo.TableName
ADD CONSTRAINT df_CreatedBy DEFAULT (USER_ID()) FOR CreatedBy;
Check the documentation for ALTER TABLE...

Related

How can I ignore default value on SQL insert statement?

I've already set default value for some of my columns.
CREATE TABLE [dbo].[TEST]
(
[id] [INT] NULL,
[fname] [VARCHAR](50) NULL,
[lname] [VARCHAR](50) NULL,
[default1] [VARCHAR](50) NULL,
[default2] [VARCHAR](50) NULL,
[default3] [VARCHAR](50) NULL
) ON [PRIMARY]
ALTER TABLE [dbo].[TEST]
ADD CONSTRAINT [DF_TEST_job] DEFAULT ('test1') FOR [default1]
ALTER TABLE [dbo].[TEST]
ADD CONSTRAINT [DF_TEST_default2] DEFAULT ('test2') FOR [default2]
ALTER TABLE [dbo].[TEST]
ADD CONSTRAINT [DF_TEST_default3] DEFAULT ('test3') FOR [default3]
Now I'm going to set all columns with default values to null in my INSERT statement sometimes.
I know that if I provide values for the columns in the INSERT, their defaults will be ignored. But I'm looking for a way to set default values off on some inserts.
I know that it might be impossible, but I want to learn it's way (if there is.
I don't fully understand what you're trying to ask here....
If you provide a value for a column - even if it's NULL, in your INSERT statement, then SQL Server will use that provided value and skip any default value defined on the column.
So by just providing NULL, you're basically doing what your title asks: ignore the default value of the column.... the default value of a column is only used if you omit that column entirely from your INSERT statement....

Timestamp column not saving data in sql table

Hi I am designing table called user-registration with few fields. I have created date and updated date and requirement is to put time stamp for created and updated fields. I googled and found only one time stamp we can have per table and value will be inserted automatically and no need to supply value to it. Please correct me if i am wrong. Currently when i insert row of data to table i am getting in time stamp field. Below is my table structure.
CREATE TABLE [dbo].[NCT_UserRegistration](
[User_Id] [int] IDENTITY(1,1) NOT NULL,
[User_EmailId] [varchar](255) NULL,
[User_Password] [varchar](512) NULL,
[User_Name] [varchar](255) NULL,
[User_MobileNum] [varchar](20) NULL,
[User_Status] [varchar](15) NULL CONSTRAINT chk_Status CHECK ([User_Status] IN ('ENABLED', 'DISABLED')),
[User_Role] [varchar](20) NULL CONSTRAINT chk_Role CHECK ([User_Role] IN ('SUPER_ADMIN','PROJECT_ADMIN')),
[User_CreatedDate] [timestamp] NULL,
[User_UpdatedDate] [datetime] NULL,
[Name] [varchar](30) NULL
)
I tried as below.
ALTER TABLE [NCT_UserRegistration]
ALTER COLUMN [User_CreatedDate] TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
and ended up with Incorrect syntax near the keyword 'DEFAULT'.
Any help would be appreciated. Thank you.
Try this in Table structure :-
User_CreatedDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

Update PK columns in table having clustered keys

I have a database with tables that have clustered primary keys. I believe the term I picked up on is use of a Natural Key. The frontend to the SQL database is programmed to affect changes to all related foreign key tables for the 3,000 selected values which I want to modify. It takes about 13 seconds per change. I have a need to do this in a much shorter timeframe if possible.
The reason for doing this is prep work to migrate to a new CMMS program.
I found reference for use of ON UPDATE CASCADE, but I am not certain this applies.
Among many references, I used the following:
https://social.technet.microsoft.com/Forums/sqlserver/it-IT/23294919-3e6a-4146-a70d-66fa155ed1b3/update-primary-key-column-in-sql-server?forum=transactsql
An example of 2 of the 15 tables having the same named [EQNUM] column follows. Table A is the table that is first modified using the frontend. I left out many columns for each table:
CREATE TABLE A
(
[EQNUM] [varchar](30) NOT NULL,
CONSTRAINT [PK_A] PRIMARY KEY CLUSTERED ([EQNUM] ASC)
)
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE B
(
[EQNUM] [varchar](30) NOT NULL,
[ColA] [varchar](10) NOT NULL,[ColB] [datetime] NOT NULL,
[ColC] [varchar](30) NOT NULL, [ColD] [varchar](30) NOT NULL,
[ColE] [varchar](30) NOT NULL, [ColF] [varchar](30) NOT NULL,
[ColG] [varchar](11) NOT NULL,[ColH] [varchar](10) NOT NULL,
[ColI] [datetime] NOT NULL,[ColJ] [varchar](15) NOT NULL,
[ColK] [int] NULL,
CONSTRAINT [PK_B]
PRIMARY KEY CLUSTERED ([EQNUM] ASC,
[ColA] ASC,[ColB] ASC,[ColC] ASC,[ColD] ASC,[ColE] ASC,
[ColF] ASC,[ColG] ASC,[ColH] ASC,[ColI] ASC,[ColJ] ASC)
)
An example of 1 of 4 sets of UPDATE queries, for which I believe the added first and last ALTER TABLE lines would allow me to affect the update:
ALTER TABLE A NOCHECK CONSTRAINT [PK_EQUIP]
UPDATE A
SET [EQNUM] = REPLACE([EQNUM],'-B','-B0')
WHERE [EQNUM] LIKE '%-A[1-9][0-5][0-9]-%' OR
[EQNUM] LIKE '%-A[1-9][A-F][0-5][0-9]-%' OR
ALTER TABLE A CHECK CONSTRAINT [PK_EQUIP]
ALTER TABLE A NOCHECK CONSTRAINT [PK_B]
UPDATE B
SET [EQNUM] = REPLACE([EQNUM],'-B','-B0')
WHERE [EQNUM] LIKE '%-A[1-9][0-5][0-9]-%' OR
[EQNUM] LIKE '%-A[1-9][A-F][0-5][0-9]-%' OR
ALTER TABLE A CHECK CONSTRAINT [PK_B]
Is it this simple, or am I missing something? Is there a better way?

Add nullable datetime column to Primary Key

I have a table with following columns:
[ClauseID] [int] NOT NULL,
[PolicyCategoryID] [int] NOT NULL,
[ExpiryDate] [smalldatetime] NULL,
By now ClauseID and PolicyCategoryID together creates the primary key. But I want ExpiryDate also be a part of primary key. To make the column not null I tried the following but it gives an error:
ALTER TABLE tblClauses_PolicyCategory
ALTER COLUMN [ExpiryDate] SMALLDATETIME NOT NULL DEFAULT '2079-06-06'
Incorrect syntax near the keyword 'DEFAULT'.
Any idea why? Is it not possible to set a default date like this?
EDIT: By bad! Default key was already set. That must be the reason it gave an error.
try this:
ALTER TABLE tblClauses_PolicyCategory
ALTER COLUMN [ExpiryDate] SMALLDATETIME NOT NULL
ALTER TABLE tblClauses_PolicyCategory ADD CONSTRAINT
cons_expiryDate DEFAULT '2079-06-06' FOR ExpiryDate
Before execute these lines, please check if exists some rows with ExpiryDate null, if yes, please, update all nullable rows to default value
I think this will help you:
CREATE TABLE tblClauses_PolicyCategory(
[ClauseID] [int] NOT NULL,
[PolicyCategoryID] [int] NOT NULL,
[ExpiryDate] [smalldatetime] NULL)
ALTER TABLE tblClauses_PolicyCategory
ALTER COLUMN [ExpiryDate] SMALLDATETIME NOT NULL
ALTER TABLE tblClauses_PolicyCategory
ADD CONSTRAINT cons_default DEFAULT '2079-06-06' FOR ExpiryDate
But, before changing ExpireDate to NOT NULL, you must populate values for existing rows in this column, and then change column to NOT NULL.

How to add multiple columns to a table and add default constraint on one of them?

I want to add 2 new columns to existing table.
One of them should be NOT NULL with default value 0
(filled in the existing rows as well).
I have tried the following syntax:
Alter TABLE dbo.MamConfiguration
add [IsLimitedByNumOfUsers] [bit] NOT NULL,
CONSTRAINT IsLimitedByNumOfUsers_Defualt [IsLimitedByNumOfUsers] DEFAULT 0
[NumOfUsersLimit] [int] NULL
go
But it throws exception. How should I write it?
You can use this:
ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [BIT] NOT NULL DEFAULT 0,
[NumOfUsersLimit] [INT] NULL
GO
or this:
ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [BIT] NOT NULL
CONSTRAINT IsLimitedByNumOfUsers_Default DEFAULT 0,
[NumOfUsersLimit] [INT] NULL
go
More: ALTER TABLE
Try this.
ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [bit] NOT NULL DEFAULT 0,
[NumOfUsersLimit] [int] NULL
To add multiple columns to a table and add default constraint on one of them-
ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [BIT] CONSTRAINT Def_IsLimitedByNumOfUsers DEFAULT(0) NOT NULL,
[NumOfUsersLimit] [INT] NULL;
GO
Each column is different;
ALTER TABLE
MamConfiguration
ADD
Configuration1 BIT NULL, --this column is nullable
Configuration2 BIT NOT NULL, --this column is not nullable
Configuration3 BIT NOT NULL DEFAULT(0), --this column is not nullable and set default value is 0(zero)
Configuration4 BIT NOT NULL CONSTRAINT DF_Configuration4 DEFAULT(0) --this column is not nullable and set default value is 0(zero) with spesific constraint name
GO