Common Table Expression
CTE is common table expression. It is a temporary named result set derived from a simple query and defined within the execution scope of a single SELECT, INSERT, UPDATE, or DELETE statement. CTE can be used for writing complex recursive queries. It is much more popular than temporary tables.
Syntax
Sample Demo
- WITH [CTEName]
- AS
- (
- SELECT column1, column2, column3 FROM [TableName] WHERE [condition]
- )
- SELECT column1, column2, column3 FROM [CTEName]
In the following example we will see how to delete duplicate records from a table using CTE.
Use the following procedure.
- We need to create a table first. Copy the CityMaster table script and execute on the SQL Server under an appropriate database.
- CREATE TABLE [CityMaster](
- [Id] [int] PRIMARY KEY ,
- [City] [varchar](50) NULL,
- [State] [varchar](50) NULL
- )
- Once the table is created we need to now insert some records into the table that includes some duplicates.
- insert into [CityMAster]
- Select 1,'Aurangabad','BIHAR' union all
- Select 2,'Aurangabad','MAHARASHTRA' union all
- Select 3,'Bijapur','KARNATAKA' union all
- Select 4,'Bijapur','CHHATTISGARH' union all
- Select 5,'Bilaspur','CHHATTISGARH' union all
- Select 6,'Bilaspur','HIMACHAL PRADESH' union all
- Select 7,'Jamui','BIHAR' union all
- Select 8,'Kullu','HIMACHAL PRADESH' union all
- Select 9,'Pune','MAHARASHTRA' union all
- Select 10,'Mumbai','MAHARASHTRA' union all
- Select 11,'Kolhapur','MAHARASHTRA' union all
- Select 12,'Nashik','MAHARASHTRA' union all
- Select 13,'Mysore','KARNATAKA' union all
- Select 14,'Raigarh','CHHATTISGARH'
- Select 15,'Aurangabad','BIHAR' union all
- Select 16,'Bilaspur','CHHATTISGARH' union all
- Select 17,'Bijapur','KARNATAKA'
- Execute the preceding script and check the data in the table by firing the following query.
- select * from [CityMaster] order by city,[state]



hemanth galiPosted Jun 7, 2017, 5:51 AM
You are deleting rows in cte, but how does it deletes rows from original table
Karthik Muthu KaruppanPosted Apr 23, 2015, 11:35 AM
nice
Khargesh RajputPosted Apr 18, 2015, 9:26 PM
Nice