Alter column properties in SQL [duplicate] - sql

This question already has answers here:
Default getdate for Insert date
(9 answers)
Closed 8 years ago.
I am trying to make a change to the data type for a column in an existing table. This column currently is empty but the table has dependencies which makes it impractical to drop and recreate the table.
The table currently looks like:
CREATE TABLE [dbo].[van_Payment](
[PaymentUID] [int] IDENTITY(1,1) NOT NULL,
[SponsorshipUID] [int] NOT NULL,
[PaymentMethodUID] [int] NOT NULL,
[Amount] [int] NOT NULL,
[Created] [int] NOT NULL,
GO
I need to change the following:
ALTER TABLE [dbo].[van_Payment]
ALTER COLUMN [Created] [smalldatetime] NOT NULL DEFAULT GETDATE(),
GO
I am getting the following error:
Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword
'DEFAULT'.
Any help with the correct syntax would be appreciated.

I don't think it possible to add default constraint using alter column syntax. Try this.
ALTER TABLE [dbo].[van_Payment]
ALTER COLUMN [Created] [smalldatetime] NOT NULL
GO
ALTER TABLE dbo.[van_Payment] ADD CONSTRAINT DF_Created DEFAULT getdate() FOR [Created];

Related

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

Unable to add column using ALTER

I'm creating a table using the following code
CREATE TABLE [dbo].[t_emp](
[empid] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[salary] [numeric](10, 2) NOT NULL,
[dept] [nvarchar](50) NOT NULL)
And also i'm trying to add column using the following code,
alter table t_emp add column ename varchar(50) not null
But i'm getting the following error,
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'column'.
Please guide me the correct way to achieve my objective.
Use Command without Column
AŁŽlter Table t_emp Add ename varchar(50) not null

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

SQL Server IDENTITY column

How can I modify this command in order to have an identity column which has five digits integer like 00000 and start from 00001 ?
CREATE TABLE [dbo].[Company]
(
[CompanyId] [bigint] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](200) NOT NULL
)
An integer does not have any leading 0 by itself. It is a formatting issue to deal with when converting the integer to a string for displaying.
If you really, really need to be able to present such a string right out of SQL, you can do it with a computed column:
CREATE TABLE [dbo].[Company](
[CompanyId] [bigint] IDENTITY(1,1) NOT NULL,
[FormattedCompanyId] AS RIGHT('0000'+ CONVERT(VARCHAR,Num),5),
[Name] nvarchar NOT NULL,
I would never use that solution myself though, formatting doesn't belong in the data store.
You need to add the leading zeros yourself. As a solution you can add an other colomn named say "formatedID" and update it with an "after insert trigger" with the value from the identity column and formatted with the leading zeros you want to.
Example :
CREATE TABLE [dbo].[Company]
(
[CompanyId] [bigint] IDENTITY(1,1) NOT NULL,
[FormattedID] [VARCHAR(20)],
[Name] [nvarchar](200) NOT NULL
)
CREATE TRIGGER ON [dbo].[Company]
FOR INSERT
AS
BEGIN
UPDATE [dbo].[Company]
FROM inserted
SET FormattedID = RIGHT('0000'+ CONVERT(VARCHAR, [dbo].[Company].CompanyId),5)
WHERE dbo.Company.CompanyId = inserted.CompanyId
END