What is the method for setting default values in SQL Server?
In SQL Server, default values can be set using two methods:
- In the CREATE TABLE statement, the DEFAULT keyword can be used to set a default value for a column when creating a table. For example:
CREATE TABLE Employee (
ID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT DEFAULT 18
);
In the example above, the default value of the Age column is set to 18.
- To modify the default value of a column, you can use the ALTER COLUMN command within the ALTER TABLE statement. For example:
ALTER TABLE Employee
ALTER COLUMN Age SET DEFAULT 18;
In the given example, set the default value of the Age column in the Employee table to 18.
Data can be inserted without providing default values using the INSERT statement regardless of the method used. For example:
INSERT INTO Employee (ID, Name) VALUES (1, 'John');
In the example above, the Age column value is not provided in the inserted data, so the default value of 18 will be used.