COMMON TABLE EXPRESSIONS(cte): It is used best used to extract the hierarchical data and it is best explained with an example: Problem Many organizations have some type of hierarchy for business processes. When it comes to large organizations, the hierarchy can get very complex and large, so building a hierarchy in a RDBMS is a tedious task. We have to create views, cursors and so on, but using a CTE in SQL Server is a better solution to retrieve hierarchy-based data. Solution Common Table Expressions (CTE) have two types, recursive and non-recursive. We will see how the recursive CTE works with examples. A recursive CTE can be explained in three parts: Anchor Query: This is the first statement which is executed. This query will give the base data for the CTE. Separator: This is the middle part where in we generally use a UNION ALL and few more operators. Recursive Query: This is the main part, this is the CTE query which refers to the same CTE by recursion. ...
Popular posts from this blog
SQL JOINS Tutorial: INNER, OUTER, LEFT, RIGHT, CROSS What are JOINS? Joins help retrieving data from two or more database tables. The tables are mutually related using primary and foreign keys. id first_name last_name movie_id 1 Adam Smith 1 2 Ravi Kumar 2 3 Susan Davidson 5 4 Jenny Adrianna 8 6 Lee Pong 10 id title category 1 ASSASSIN'S CREED: EMBERS Animations 2 Real Steel(2012) Animations 3 Alvin and the Chipmunks Animations 4 The Adventures of Tin Tin Animations 5 Safe (2012) Action 6 Safe House(2012) Action 7 GIA 18+ 8 Deadline 2009 18+ 9 The Dirty Picture 18+ 10 Marley and me Romance Types of joins Cross JOIN Cross JOIN is a simplest form of JOINs which matches each row from one database table to all rows of another. In other words it gives us combinations of each row of first table with all records in second table. Suppose we want to get all member records against all the movie records, we can use the script shown below to ge...

Comments
Post a Comment