Oct 21, 2014

DEFAULT constraint in sql server

DEFAULT – This constraint provides a default value when specified non for this column.

Example-
Following create a table PRODUCT, column DTCREATE has default value GETDATE() it will store system’s date-time by default if value is not specified for this column.

CREATE TABLE PRODUCT
(
ID INT NOT NULL,
SKU VARCHAR(20) NOT NULL,
TITLE VARCHAR(200) NOT NULL,
PRICE MONEY NOT NULL,
DISCRIPTION VARCHAR(2000)  NULL,
DTCREATE DATETIME DEFAULT GETDATE()
)

If PRODUCT table has already been created and you want apply default price in PRICE column use following query (for SQL server).


ALTER TABLE PRODUCT ADD CONSTRAINT DF_SomePrice DEFAULT 20.00 FORPRICE