Command to set a default value for a column in SQL Server

Asked

Viewed 1,108 times

-1

Hello, I want to know the command to set a value like default in SQL server.

The table name is "Table" and the column name you want to change is "COLUNA2".

2 answers

3

To set a default value of a table column you must use the operator DEFAULT. You can inform you when creating your table:

CREATE TABLE tabela (
  id INT NOT NULL PRIMARY KEY,
  coluna1 VARCHAR(100),
  coluna2 INT DEFAULT 1
);

Or to change the column:

ALTER TABLE tabela ADD CONSTRAINT coluna2_default DEFAULT 1 FOR coluna2;

In the above examples the value 1 will be defined in the column if not reported in the insertion:

INSERT INTO tabela(id, coluna1)
            VALUES(1, 'blablabla');

Resulting in registration:

| id  | coluna1   | coluna2 |
| --- | --------- | ------- |
| 1   | blablabla | 1       |

Using Transact-SQL to specify a pattern

There are several ways in which you can specify a default value for a column using SSMS to send T-SQL.

  • Thanks for the answer

  • @Don’t forget to accept the answer if it has helped you

1

Julio, good afternoon!

If you have already set the table to have a default value in creating it, there is no need to pass value to the column when you do the Insert.

Creation example with Default value:

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    City varchar(255) DEFAULT 'Sandnes'
); 
  • 1

    In case I didn’t set up, but I found the answer. Thankful!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.