You are on page 1of 18

----------------------------------SQL------------------------------------------------------------Used by all relational database management systems: SQL Server(T), Oracle(PL),DB2,Sybase(T), MySQL, PostgreSQL, Informix, etc.

PL/SQL-> proprietary procedural language used by Oracle TSQL -> proprietary procedural language used by Microsoft in SQL Server. ANSII SQL->American National Standards Institute ----------------TSQL(Transact SQL)---------Superset of ANSII SQL----------------------------------DDL->Data Definition Language-----Define database Objects(Tables,View) DML->Data Manipulation Language---Manipulate data inside database ObjectsRows and columns DCL->Data Control Language--------Control access/permissions to access objects/data inside objects ----------------T Sql Commands---------------------------------------------------------------------DDL-Create,Alter,Drop,Truncate DML-Select,Insert,Update,Delete DCL-Grant,Deny,Revoke ---------------------DDL---------------------------------------------------------------Create---------Creates/Define structure of Object Alter----------Modify Structure of Object Drop-----------Removes Data& structure Truncate-------Data/Rows are removed----Object/Table structure remains ------------------------------List of database Objects---------------------------------Tables,Views,Indexes,Stored Procedures,Functions,Triggers,Jobs,Alerts,Statistics Local temporary tables ,Global temporary tables,table variables CREATE PARTITION FUNCTION,CREATE PARTITION SCHEMA ------------------------Change Default Output-------------------------------------------SQL Server Management Studio currently supports query execution results to be displayed in three different ways: Results to Grid, Results to Text and Results to File. Ssms>Tools>Options>Query Results> expand SQL Server and then select General ***************************************************************************** ****************** -----------------------------Create objects in the database------------------------------------------------1.Create Database******************************************************************** CREATE DATABASE <DBName> ON PRIMARY ---(filegroupname ) ( NAME = <'DB Name'>, FILENAME = <'path\.mdf'> , SIZE = 2MB , MAXSIZE = 3mb/UNLIMITED, FILEGROWTH = 100KB ) LOG ON ( NAME = 'Name_Log', FILENAME = <'Path\.ldf'> , SIZE = 520KB , MAXSIZE = 2048GB , FILEGROWTH = 100KB ) --------------------------------------------------------------------------------------------------Drop database BartronicsNovember USE [master] GO

CREATE DATABASE BartronicsNovember ON PRIMARY ( NAME = 'BartronicsNov', FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\BartronicsNov.mdf' , SIZE = 3MB , MAXSIZE = 20mb, FILEGROWTH = 100KB ) LOG ON ( NAME = 'BartronicsNov_Log', FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\BartronicsNov_Log.ldf' , SIZE = 520KB , MAXSIZE = 20mb , FILEGROWTH = 100KB ) GO --------------------2.Create Table******************************************************************** CREATE TABLE < Table_Name> ( ColumnName1 datatype(Size), ColumnName2 datatype(Size) ) ---------------------------------------------------------------------------------------------------Use BartronicsNovember CREATE TABLE Employee ( Emp_id int , Emp_name varchar(20), Salary money , DOJ DateTime ) ----------------------------------------------------------------------------select * from Employee Insert into Employee values (1,'Rekha',60,'2/12/2009') Insert into Employee values ('Rekha',1,60,'2/12/2009')--Error Insert into Employee values (null,null,null,null) Insert into Employee values (0,'null',0,0) Insert into Employee values (0,'0',0,0) ------------------Add 0 Insert into Employee values ( ,' ', , ) --------------Add Spaces????????????????????? Drop table Employee --Common kinds of constraints are: not null -- value in a column must not be NULL unique -- value(s) in specified column(s) must be unique for each row in a table primary key -- value(s) in specified column(s) must be unique for each row in a table and not be NULL; normally each table in a database should have a primary key - it is used to identify individual records foreign key -- value(s) in specified column(s) must reference an existing record in another table (via it's primary key or some other unique constraint) check -- an expression is specified, which must evaluate to true for constraint to be satisfie --No Duplicate ConstraintNames on Database --No Duplicate ConstraintNames on Tables --No Duplicate PK Constraints on Tables --Can Have Duplicate FK,Check,Unique Constraints on Tables -----------------------PK******************************************************************** Create TABLE EmployeePK

( Emp_id int primary key, ----------- Column level Constraint Emp_name varchar(100), Salary money , DOJ DateTime ) -------------------------PKC-------Column level Constraint************************************** CREATE TABLE EmployeePKC ( Emp_id int , ------------------- Column level Constraint Emp_name varchar(100), Salary money , DOJ DateTime CONSTRAINT pk_Employee_eid PRIMARY KEY(Emp_id) ); -------------------------PK Constraint :See Index created----********************************* Select * from sys.indexes where object_id=object_id('EmployeePKC') Select * from sys.indexes where object_id=object_id('EmployeePK') -------------------------------------------------------------------------------------------------No Duplicate Constraint on Database -------------------------Cannot Create Same Constraint On Another Table***************************ERROR CREATE TABLE EmployeePKC2 ( Emp_id int , ------------------- Column level Constraint Emp_name varchar(100), Salary money , DOJ DateTime CONSTRAINT pk_Employee_eid PRIMARY KEY(Emp_id) ); --------------------------Change PK ************************************************************ Alter TABLE EmployeePKC Add CONSTRAINT pk_Employee_eid PRIMARY KEY(Emp_id)---PK Duplicate :Same Column--Error Alter TABLE EmployeePKC Add CONSTRAINT pk_Employee_eid2 PRIMARY KEY(Emp_id)--PK Duplicate----Error Alter TABLE EmployeePKC Add CONSTRAINT pk_Employee_eid unique(Emp_id) Alter TABLE EmployeePKC Drop CONSTRAINT pk_Employee_eid Alter TABLE EmployeePKC Add CONSTRAINT pk_Employee_eid Unique(Emp_id) Alter TABLE EmployeePKC Add CONSTRAINT pk_Employee_eid2 PRIMARY KEY(Emp_name)----PK Duplicate :Diff Column -------------------------DROP ALL----------------------------------------Alter TABLE EmployeePKC drop CONSTRAINT pk_Employee_eid Alter TABLE EmployeePKC drop CONSTRAINT pk_Employee_eid2 Alter TABLE EmployeePK drop CONSTRAINT PK__Employee__263E2DD300551192 -----------------------FK------------------------------------------------Drop Table EmployeeFK Drop Table EmployeePK Create TABLE EmployeePK ( Emp_id int primary key, ----------- Column level Constraint Emp_name varchar(100), Salary money , DOJ DateTime

) Create TABLE EmployeeFK ( Emp_id int PRIMARY KEY, Emp_idFK int FOREIGN KEY(Emp_IDFK) references EmployeePK(Emp_ID) , ------------------ Column level Constraint Emp_name varchar(30), Salary money , DOJ DateTime --CONSTRAINT fk FOREIGN KEY(StudentID) references EmployeePK(Emp_ID) ); ----------------------FK Constraint----------------------------------------------------CREATE TABLE EmployeeFKC2 ( Emp_id int PRIMARY KEY, Emp_idFKC int , ------------------- Column level Constraint Emp_name varchar(30), Salary money , DOJ DateTime CONSTRAINT Emp_idFKC2 FOREIGN KEY (Emp_idFKC3) references EmployeePK(Emp_ID) ); --------------------------------------------------------------------------------------------Drop TABLE EmployeeFK ----------------------Composite Key---------------------------------------------------------CREATE TABLE UserGroup ( [User_Id] INT NOT NULL, [Group_Id] INT NOT NULL CONSTRAINT PK_UserGroup PRIMARY KEY NONCLUSTERED ([User_Id], [Group_Id]) ) --------------------------------------------------------------------------------------------CREATE TABLE EmployeeNewKeyfull ( Emp_name varchar(30), Salary money , DOJ DateTime ) Insert into EmployeeNewKeyfull values ('DEEPA',1000,'05/20/85') ALTER TABLE EmployeeNewKeyfull Add Emp_id INT NOT NULL Truncate table EmployeeNewKeyfull --ALTER TABLE EmployeeNewKey ALTER COLUMN Emp_id INT NOT NULL ALTER TABLE EmployeeNewKey ADD PK_New INT PRIMARY KEY (Emp_id) Select * from EmployeeNewKey Drop table EmployeeNewKey ------------------Add primary key column to a filled table------------------ALTER TABLE <TABLE_NAME> ALTER COLUMN <COLUMN_NAME> INT NOT NULL ------------------Add primary key column to a filled table-----use Identity-----IF OBJECT_ID ('dbo.new_employees', 'U') IS NOT NULL DROP TABLE new_employees;

GO CREATE TABLE new_employees ( id_num int IDENTITY(1,1), fname varchar (20), minit char(1), lname varchar(30) ); INSERT new_employees (fname, minit, lname) VALUES ('Karin', 'F', 'Josephs'); ('Pirkko', 'O', 'Koskitalo'); ------------------Add identity column to an existing table-----------------?????????????/ CREATE TABLE new_employeesidentity ( fname varchar (20), minit char(1), lname varchar(30) ); INSERT new_employees (fname, minit, lname) VALUES ('Karin', 'F', 'Josephs'); ('Pirkko', 'O', 'Koskitalo'); id_num int IDENTITY(1,1), ------------------Add primary key column to an empty table------------------Select * from ALTER TABLE <TABLE_NAME> ALTER COLUMN <COLUMN_NAME> INT NOT NULL CREATE TABLE EmployeeNewKey ( Emp_name varchar(30), Salary money , DOJ DateTime ) ALTER TABLE EmployeeNewKey Add Emp_id INT NOT NULL --ALTER TABLE EmployeeNewKey ALTER COLUMN Emp_id INT NOT NULL ALTER TABLE EmployeeNewKey ADD PK_New INT PRIMARY KEY (Emp_id) Select * from EmployeeNewKey Drop table EmployeeNewKey ------------------set primary key on existing column------------------ALTER TABLE Table name ADD PRIMARY KEY (persID) -----------------------------------CREATE TABLE Employee_NotNull ( Emp_id int not null , Emp_name varchar(30) not null, Salary money not null , DOJ DateTime not null ) Insert into Employee_NotNull values (null,null,null,null) Insert into Employee_NotNull values (99,'null value',40,'12/12/2012') Select * from Employee_NotNull ----------------------Create Unique key---------------------------------------------------------------------------UK----------UNIQUE CONSTRAINT---------------------------CREATE TABLE EmployeeUK

( Emp_id int , ------------------- Column level Constraint Emp_name varchar(100) UNIQUE, Salary money , DOJ DateTime ); Insert into EmployeeUK values (1,'DEEPA',1000,'05/20/85') Insert into EmployeeUK values (1,'roopa',1000,'05/20/85') Insert into EmployeeUK values (1,NULL,1000,'05/20/85') Insert into EmployeeUK values (1,'Rekha',1000,'05/20/85') Select * from EmployeeUK CREATE TABLE EmployeeUK_NC ( Emp_id int , ------------------- Column level Constraint Emp_name varchar(100) UNIQUE NONCLUSTERED, Salary money , DOJ DateTime ); --------------------------------------------------------------------CREATE TABLE EmployeeUK_C ( Emp_id int UNIQUE CLUSTERED, ------------------- Column level Constraint Emp_name varchar(100) UNIQUE CLUSTERED,-------------------Error Salary money UNIQUE nonCLUSTERED, DOJ DateTime UNIQUE nonCLUSTERED ); ------------------------------------------------------------------------CREATE TABLE EmployeeUKC ( Emp_id int, Emp_name varchar(30), Salary money , DOJ DateTime CONSTRAINT ukc_Emp_id unique (Emp_ID) ); ---------------------Creating Default Constraint----------------------------Create TABLE EmployeeDC (Emp_id int, Salary money DEFAULT 500) INSERT EmployeeDC (Emp_id )VALUES (3) SELECT * FROM EmployeeDC DROP TABLE EmployeeDC ---------------------Creating Check Constraint----------------------------Create TABLE EmployeeCC (Emp_id int, Salary money Check (salary > 500)) INSERT into EmployeeCC VALUES (3,600) INSERT into EmployeeCC VALUES (3,400) SELECT * FROM EmployeeCC Drop Table EmployeeCC CREATE TABLE Customer1 (SIDA integer CHECK (SIDA > 0), Last_Name varchar (30), First_Name varchar(30)); INSERT into Customer1 VALUES (400,'A','B') INSERT into Customer1 VALUES (-400,'A','B') Drop Table Customer1

----------------------Prevent Constraint to Allow NULL---------------------ALTER TABLE TestTable ADD CONSTRAINT CK_TestTable_Col2 CHECK (Col2 > 0 AND Col2 IS NOT NULL) GO -- Insert will throw an error INSERT INTO TestDB.dbo.TestTable (ID, Col1, Col2) VALUES(1,1,NULL) ----------------------Alter Constraint-----------------------------------We cannot alter the constraint, only thing we can do is drop and recreate it. --------------------Drop TABLE/Constraint--------------------------------------Drop table EmployeeRepeating_Constraint1,EmployeePK,EmployeePKC,EmployeeFK,EmployeeFKC,E mployeeUK Drop Constraint pk_Employee_eid CREATE TABLE EmployeeRepeating_Constraint1 ( Emp_id int, Emp_name varchar(30), CONSTRAINT ukc_Emp_id unique (Emp_ID) ); Drop Constraint ukc_Emp_id; CREATE TABLE EmployeeRepeating_Constraint2 ( Emp_id int, Emp_Desig varchar(30), CONSTRAINT ukc_Emp_id unique (Emp_ID) ); ---------------------------------------------------------------------------------------Select * from System.Data.Constraint Select * from System.Data.UniqueConstraint *****************************Alter Objects in DB*********************************************************** ---1.ALTER DATABASE ----------------------------------------------------------Syntax: ALTER DATABASE <old_database_name> MODIFY NAME = <new_database_name> Use Master use AdventureWorks ALTER DATABASE BartronicsSept MODIFY NAME = BartronicsSeptember ALTER DATABASE BartronicsSeptember MODIFY NAME = BartronicsSept ---2.Alter Table ------------------------ADD COLUMN :-----------------------------------------------ALTER TABLE <table_name> ADD <column > <Data Type>....n ALTER TABLE EmployeePK ADD Designation varchar(20) Select * from EmployeePK ----------------------- MODIFY COLUMN datatype:-------------------------------------ALTER TABLE <table_name> ALTER COLUMN <column_Name> <New_Data Type> ALTER TABLE EmployeePK Alter Column Designation varchar(30) Select * from EmployeePK ----------------------- Drop COLUMN datatype:----------------------------------------

ALTER TABLE dbo.doc_exb DROP COLUMN column_b ; ------------------------Adding a column with a constraint---------------------------ALTER TABLE dbo.doc_exc ADD column_b VARCHAR(20) NULL CONSTRAINT exb_unique UNIQUE ; ------------------------Adding an unverified CHECK constraint to an existing column--CREATE TABLE dbo.doc_exd ( column_a INT) ; GO INSERT INTO dbo.doc_exd VALUES (-1) ; GO ALTER TABLE dbo.doc_exd WITH NOCHECK ADD CONSTRAINT exd_check CHECK (column_a > 1) ; GO EXEC sp_help doc_exd ; GO DROP TABLE dbo.doc_exd ; GO ----------------------- Adding a DEFAULT constraint to an existing column---------------CREATE TABLE dbo.doc_exz ( column_a INT, column_b INT) ; GO INSERT INTO dbo.doc_exz (column_a)VALUES ( 7 ) ; GO ALTER TABLE dbo.doc_exz ADD CONSTRAINT col_b_def DEFAULT 50 FOR column_b ; GO INSERT INTO dbo.doc_exz (column_a) VALUES ( 10 ) ; GO SELECT * FROM dbo.doc_exz ; GO DROP TABLE dbo.doc_exz ; GO ------------------------------------------------------------------------------------------Use BartronicsJune Select * from Employee Alter table dbo.Employee Add DeptNo int, Dept_Name varchar(50) EXEC sp_help dbo.Employee ------------------------------------------------------------------------------------------ALTER TABLE Employee ALTER COLUMN deptno char(50) -------------------------RENAME Column name-------------------------------------------------It is not possible to rename a column using the ALTER TABLE statement in SQL Server. --Use sp_rename instead. SP_RENAME [<Table_name>.<Column_name>],<column_name> -------------------------------------------------------------------------------------------SP_RENAME [EmployeeMay.DeptNo],Dept_Number ---------- Clean up system --remove all Constrints---------------------------------------------------------------------------------USE MASTER GO

ALTER DATABASE TestDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE; GO DROP DATABASE TestDB GO ------------------------------------Use master Drop database BartronicsSept Drop dbo.EmployeePK ***************************************************************************** *************** --------------------------Truncate OBJECTS---------------------------------------------After a DELETE statement is executed, the table can still contain empty pages. --TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes, and so on remain. -- To remove the table definition in addition to its data, use the DROP TABLE statement. --If the table contains an identity column, the counter for that column is reset to the seed value defined for the column. --If no seed was defined, the default value 1 is used. To retain the identity counter, use DELETE instead. You cannot use TRUNCATE TABLE on tables that: --1.Are referenced by a FOREIGN KEY constraint. (You can truncate a table that has a foreign key that references itself.) --2.Participate in an indexed view. --3.Are published by using transactional replication or merge replication. ----------------------------Truncate Table----------------------------------------USE AdventureWorks; GO 'SELECT * INTO BartronicsJuly.NewContact from AdventureWorks.Person.CountryRegion SELECT Contact.ContactID INTO NewContact.ContactID from Person.Contact SELECT * from dbo.NewContact2' ---------------------------------------------------------------------------------USE AdventureWorks; Select * from ContactID SELECT * INTO ContactID from Person.Contact SELECT COUNT(*) AS BeforeTruncateCount FROM ContactID; GO TRUNCATE TABLE ContactID; GO SELECT COUNT(*) AS AfterTruncateCount FROM ContactID; Select * from ContactID; Drop Table ContactID

-------------------------------------------------------------------------------------Select * from dbo.NewContact ***************************************************************************** **************** --------------------------DROP OBJECTS-------------------------------------------Drop Table <Table_Name> Drop Table Employee Drop Table NewContact1 Select * from dbo.NewContact1 --------------------------------------------------------------------------------------Use Master Drop Database Bartronics3 ---------------------------------------------------------------------------------------Difference between Drop & Truncate & Delete? USE Bartronics Select * FROM dbo.Customer truncate rowguid from dbo.Customer --------------------------------------------------------------------------------------------CREATE TABLE <table name> ( <Columnname 1> <data type 1><Size>, ... <Columnname n> <data type n><Size>,); ALTER TABLE <table name> ADD CONSTRAINT <constraint name> PRIMARY KEY (<attribute list>); ALTER TABLE <table name> ADD CONSTRAINT <constraint name> FOREIGN KEY (<attribute list>) REFERENCES <parent table name> (<attribute list>); DROP TABLE <table name>; TRUNCATE TABLE dbo.Employee_Test1; ALTER TABLE <table name> DROP CONSTRAINT <constraint name>; Data manipulation language INSERT INTO <table name> VALUES (<value 1>, ... <value n>); UPDATE <table name> SET <attribute> = <expression> WHERE <condition>; DELETE FROM <table name> WHERE <condition>; GRANT select, insert ON customers TO webuser; -----------------------Create primary key-------------------------------------------------CREATE TABLE Student ( Stu_id int primary key, ----------- Column level Constraint Stu_name varchar(100),

Course Varchar(50) , Accomodation Varchar(50) ) -------------Create a table Copy without Data--------------------------------------------Copy only the structure of an existing table into new table SELECT * INTO tblNew FROM tblOld WHERE 1=2 command the new table's numeric fields are switched to Auto and all decimal data is lost. How to copy constraints of old_table to new_table? Copy only the structure with data of an existing table into new table SELECT * INTO tblNew FROM tblOld SELECT TOP 0 * INTO tblNew FROM tblOld CREATE TABLE TABLENAME(NEWTABLE) AS SELECT * FROM TABLENAME(OLDTABLE) WHERE 21=2 ------------SQL: CREATE a table from another table You can also create a table from an existing table by copying the existing table's columns. It is important to note that when creating a table in this way, the new table will be populated with the records from the existing table (based on the SELECT Statement). Syntax #1 - Copying all columns from another table The basic syntax is: CREATE TABLE new_table AS (SELECT * FROM old_table); For Example: CREATE TABLE suppliers AS (SELECT * FROM companies WHERE id > 1000); This would create a new table called suppliers that included all columns from the companies table. If there were records in the companies table, then the new suppliers table would also contain the records selected by the SELECT statement. Syntax #2 - Copying selected columns from another table The basic syntax is: CREATE TABLE new_table AS (SELECT column_1, column2, ... column_n FROM old_table); For Example: CREATE TABLE suppliers AS (SELECT id, address, city, state, zip FROM companies

WHERE id > 1000); This would create a new table called suppliers, but the new table would only include the specified columns from the companies table. Again, if there were records in the companies table, then the new suppliers table would also contain the records selected by the SELECT statement. Syntax #3 - Copying selected columns from multiple tables The basic syntax is: CREATE TABLE new_table AS (SELECT column_1, column2, ... column_n FROM old_table_1, old_table_2, ... old_table_n); For Example: CREATE TABLE suppliers AS (SELECT companies.id, companies.address, categories.cat_type FROM companies, categories WHERE companies.id = categories.id AND companies.id > 1000); This would create a new table called suppliers based on columns from both the companies and categories tables. Frequently Asked Questions Question: How can I create a table from another table without copying any values from the old table? Answer: To do this, the basic syntax is: CREATE TABLE new_table AS (SELECT * FROM old_table WHERE 1=2); For Example: CREATE TABLE suppliers AS (SELECT * FROM companies WHERE 1=2); '------------------------------------------------------------------------------------------' ---------------------------------DCL COMMANDS--------------------------------------------------------1) GRANT SELECT, INSERT, UPDATE, DELETE ON album, song TO Elvis WITH ADMIN OPTION The database may be accessed by a wide public, grant them only the SELECT statement. REVOKE INSERT, UPDATE, DELETE ON album, song TO PUBLIC 2) Create a group of users, which can add and modify records, but not delete them. CREATE ROLE editors GRANT SELECT, INSERT UPDATE ON album, song TO editors 3) You have got new guy in your team and you want to authorize him to delete records. His user name is JBlack GRANT editors, DELETE ON album, song TO JBlack

4) Once again you are alone to maintain the CD catalog, because all your coworkers are gone. Only the editors role is left and useless. Delete it. DROP ROLE editors ------------------------------------TCL COMMANDS/TSQL Commands---------------------------------------1.COMMIT - Saves work done in transactions 2.ROLLBACK - Restores database to original state since the last COMMIT command in transactions 3.SAVE TRANSACTION - Sets a savepoint within a transaction USE tempdb Alter TABLE ValueTable ([value] int) DECLARE @TransactionName varchar(20) = 'Transaction1' --The following statements start a named transaction, --insert two rows, and then roll back --the transaction named in the variable @TransactionName. --Another statement outside of the named transaction inserts two rows. --The query returns the results of the previous statements. BEGIN TRAN @TransactionName INSERT INTO ValueTable VALUES(1), (2) -----Commit Transaction ROLLBACK TRAN @TransactionName; INSERT INTO ValueTable VALUES(3),(4) SELECT [value] FROM ValueTable DROP TABLE ValueTable; ------------------------------------------------------------------------------------------We recommend using table variables instead of temporary tables. Temporary tables are useful when indexes must be created explicitly on them, or when the table values must be visible across multiple stored procedures or functions. Generally, table variables contribute to more efficient query processing. For more information, see table (Transact-SQL). Partitioned Tables Before creating a partitioned table by using CREATE TABLE, you must first create a partition function to specify how the table becomes partitioned. A partition function is created by using CREATE PARTITION FUNCTION. Second, you must create a partition scheme to specify the filegroups that will hold the partitions indicated by the partition function. A partition scheme is created by using CREATE PARTITION SCHEME. Placement of PRIMARY KEY or UNIQUE constraints to separate filegroups cannot be specified for partitioned tables. For more information, see Partitioned Tables and Indexes. -------------------------------------------------------Add PK column to an empty table------------------Select * from ALTER TABLE <TABLE_NAME> ALTER COLUMN <COLUMN_NAME> INT NOT NULL CREATE TABLE EmployeeNewKey ( Emp_name varchar(30), Salary money , DOJ DateTime )

ALTER TABLE EmployeeNewKey Add Emp_id INT NOT NULL --ALTER TABLE EmployeeNewKey ALTER COLUMN Emp_id INT NOT NULL ALTER TABLE EmployeeNewKey ADD PK_New INT PRIMARY KEY (Emp_id) Select * from EmployeeNewKey Drop table EmployeeNewKey ------------------set primary key on existing column------------------ALTER TABLE Table name ADD PRIMARY KEY (persID) -----------------------------------CREATE TABLE Employee_NotNull ( Emp_id int not null , Emp_name varchar(30) not null, Salary money not null , DOJ DateTime not null ) Insert into Employee_NotNull values (null,null,null,null) Insert into Employee_NotNull values (99,'null value',40,'12/12/2012') Select * from Employee_NotNull -------------------------------------------------------------Referential actions Main article: Propagation constraint Because the database management system enforces referential constraints, it must ensure data integrity if rows in a referenced table are to be deleted (or updated). If dependent rows in referencing tables still exist, those references have to be considered. SQL:2003 specifies 5 different referential actions that shall take place in such occurrences: CASCADE RESTRICT NO ACTION SET NULL SET DEFAULT -------------------------

Arguments ------------------------------------------------------------------------------<partition_by_clause> Divides the result set produced by the FROM clause into partitions to which the DENSE_RANK function is applied. For the PARTITION BY syntax, see OVER Clause (Transact-SQL). --------------------------------------------When TOP is used with INSERT, UPDATE, MERGE, or DELETE, the ... TOP cannot be used in an UPDATE and DELETE statements on partitioned views. ---------------------------------

----------------------------Create objects in the database------------------------------------CREATE TABLE <Name> ( <Column1> <datatype><constraint/Default>, <columnN><datatype ><constraint/Default>, ) ----------------------------Column level Constraint------------------------------------------CREATE TABLE Employee ( Emp_id int primary key, -- Column level Emp_name varchar(100), Salary money, DOJ DateTime ) -------------------------------------------------------------------------------------CREATE TABLE Products ( ProductID INT, ProductName VARCHAR(25) CONSTRAINT pk_products_pid PRIMARY KEY(ProductID) ); GO ---------------------------ADD COLUMN :-----------------------------------------ALTER TABLE <table_name> ADD <column 1> <Data Type> ---------------------------------------------------------------------------------Alter table employee Add (dept_no int, dept_name varchar(50)) -------------------------MODIFY COLUMN:---------------------------------------------ALTER TABLE <table_name> ALTER COLUMN <column 1> <New Data Type> ALTER TABLE Employee ALTER COLUMN dept_no varchar(50) -------------------------RENAME TABLE:-------------------------------------------------------It is not possible to rename a column using the ALTER TABLE statement in SQL Server. --Use sp_rename instead. SP_RENAME [<Table_name>.<Column_name>],<column_name> -------------------------------------------------------------------------------------------SP_RENAME [Employee.DOJ],DateOfJoining --------------------------DROP COLUMN:j-------------------------------------

About 1,810,000 results (0.17 seconds)

Search Results

Difference between varchar(max) and varchar(8000) www.sqlservercentral.com/Forums/Topic647815-145-1.aspxShare

41 posts - Feb 2, 2009 whats the actual difference between varchar(max) and varchar(8000). Is the difference applies same for nvarchar(max) and nvarchar(8000). ---------------------------------------------

DML Event Notification social.msdn.microsoft.com ... SQL Service BrokerShare

7 posts - Dec 1, 2008 i read infromation about event notification allow to capture DML events. I found how to capture DDL and trace events but what kind of DML ... -------------------------------------------Serializable Snapshot Isolation

Potential inconsistency problems arising from write skew anomalies can be fixed by adding (otherwise unnecessary) updates to the transactions in order to enforce the serializability property.[7] ------------------------------------Using a cursor with dynamic SQL in a stored procedure

up vote8down votefavorite 2

I have a dynamic SQL statement I've created in a stored procedure. I need to iterate over the results using a cursor. I'm having a hard time figuring out the right syntax. Here's what I'm doing. SELECT @SQLStatement = 'SELECT userId FROM users' DECLARE @UserId DECLARE users_cursor CURSOR FOR EXECUTE @SQLStatment --Fails here. Doesn''t like this

You might also like