Monday, January 14, 2013

Masukkan Default kepada Field SQL

Credit to:


Salam..

Aku bapok maleh nak translate.. Kepada sesiapa yang kurang faham BI bleh ler email aku seperti berikut
sleppar@yahoo.com atau tinggal kat comment..


In SQL Server there are two ways to add a column with a default value.

Add Default Value to Existing Column

-- Add default to existing column DateOfHire:
ALTER TABLE [dbo].[Employees] ADD  DEFAULT (getdate()) FOR [DateOfHire]

-- Add default value to existing column IsTerminated
ALTER TABLE [dbo].[Employees] ADD  DEFAULT ((0)) FOR [IsTerminated]

Add New Column with Default Value

-- Add new column DateOfHire with default
ALTER TABLE Employees ADD DateOfHire datetime DEFAULT (GETDATE())

-- Add new column IsTerminated with default
ALTER TABLE Employees ADD IsTerminated datetime DEFAULT (0)

Add Default Value with Create Table

CREATE TABLE [dbo].[Employees]
(
    [EmployeeID] [INT] IDENTITY(1,1) NOT NULL,
    [FirstName] [VARCHAR](50) NULL,
    [LastName] [VARCHAR](50) NULL,
    [SSN] [VARCHAR](9) NULL,
    -- Add default of zero
    [IsTerminated] [bit] NOT NULL DEFAULT ((0)) ,
    -- Add default of getdate()
    [DateAdded] [datetime] NULL DEFAULT (getdate()),
    [Comments] [VARCHAR](255) NULL,
    [DateOfHire] [datetime] NULL
)
Share: