Saturday, February 21, 2009

SQL Syntax Reference

MS SQL
-- Creating a UNIQUE Constraint to exist table
 ALTER TABLE <table_name> ADD CONSTRAINT <constraint_name> UNIQUE(<column_name>)

--Add a Column into table
ALTER TABLE <table_name> ADD <column_name> CHAR(1) NOT NULL DEFAULT '0'
--Change Column
ALTER TABLE <table_name> ALTER COLUMN <column_name> CHAR(1) NOT NULL DEFAULT '0'

-- Rename column
SP_RENAME '<table_name>.<original_column_name>' , '<new_column_name>', 'COLUMN'
GO
-- Rename table name
SP_RENAME '<original_table_name>' , 'new_table_name';
GO

-- Check if column exist (available for SQL Server 2000)
IF NOT EXISTS (SELECT column_name FROM INFORMATION_SCHEMA.columns
                WHERE table_name = 'MyTable' AND column_name='my_column_name')
    ... do anything you do here.
GO

-- Check if table exist (available for SQL Server 2000)
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'myTable')
    DROP TABLE myTable;
GO


-- Insert data into IDENTITY  INCREMENT column
SET IDENTITY_INSERT [TableName1] ON;
INSERT INTO [TableName1](...)VALUES(...);
SET IDENTITY_INSERT [TableName1] OFF;


MySQL
-- Add a column to table
ALTER TABLE table_1 ADD COLUMN column_1 INT(10) NOT NULL;