Tuesday, 29 November 2011

Alter Example


--ADD Column
IF NOT EXISTS(Select * from INFORMATION_SCHEMA.COLUMNS
where Table_name='tblsample' and Column_name='MobileNo')
BEGIN
ALTER TABLE tblsample add MobileNo bigint NULL
END

--Create Table
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS         
WHERE TABLE_NAME = 'TblReportMaster' )       
BEGIN       
CREATE TABLE [dbo].[TblReportMaster](       
 [ReportID] [int] NULL,       
 [ReportDisplayName] [nvarchar](100) NULL,       
 [SPName] [nvarchar](100) NULL       
) ON [PRIMARY]       
END

--DROP COLUMN
IF  EXISTS(Select * from INFORMATION_SCHEMA.COLUMNS where Table_name='tblsample' and Column_name='SEX')
BEGIN
ALTER TABLE tblsample
DROP COLUMN SEX
END

--Set Primary key and Foreign Key
IF EXISTS(Select * from INFORMATION_SCHEMA.COLUMNS where Table_name='tblsample' and Column_name='SEX')
BEGIN
ALTER TABLE salesman
ADD CONSTRAINT prim_sales PRIMARY KEY (no),
CONSTRAINT foreign_sales FOREIGN KEY(product_no)
REFERENCES product
END

No comments:

Post a Comment