1

In MSSQL 2014 I would like to use an update syntax which is adding a new column with a default value. Is this possible somehow?

asked Oct 3, 2018 at 9:26
4

3 Answers 3

5

Something Like below:

alter table myTable add myNewColumn nvarchar(20) default 'myDefaultValue' not null
answered Oct 3, 2018 at 9:29

Comments

2

Here is a complete reproducible example.

Create table

CREATE TABLE employees
( employee_id INT NOT NULL,
 last_name VARCHAR(50) NOT NULL,
 first_name VARCHAR(50) NOT NULL,
 salary MONEY
);
INSERT INTO employees
VALUES (1, 'Miller', 'Peter', 80000);
INSERT INTO employees
VALUES (2, 'Myer', 'Joana', 90000);

Check contents

SELECT * FROM employees;
employee_id last_name first_name salary 
1 Miller Peter 80000 
2 Myer Joana 90000 

Add new column with default value

ALTER TABLE employees
ADD email VARCHAR(50) DEFAULT '[email protected]' NOT NULL;

Check the result

SELECT * FROM employees;
employee_id last_name first_name salary email
1 Miller Peter 80000 [email protected]
2 Myer Joana 90000 [email protected]

Here is a SQL fiddle with this example.

answered Oct 3, 2018 at 9:56

Comments

1

Try This :-

CREATE TABLE employees
( employee_id INT NOT NULL DEFAULT 0,
 last_name VARCHAR(50) NOT NULL DEFAULT 'jon',
 first_name VARCHAR(50) NOT NULL DEFAULT 'jona',
 salary MONEY DEFAULT 0
);
ALTER TABLE employees ADD designation VARCHAR(50) DEFAULT 'TL' NOT NULL; 
answered Oct 3, 2018 at 10:27

3 Comments

This creates a new table with default values, yes. But it does not update an existing table, which I think OP was after.
Please try now I Added Alter Query also
Hey Prakash, your SQL statement is faulty. You are adding a constraint instead of a column (and also reference #employees instead of employees). Happy coding!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.