SQL Common Table Expression (CTE)
SQL Server has a very powerful feature that has been added for the programmers' benefit: Common Table Expression (CTE). Common Table Expressions, or CTE, are a new construct introduced in Microsoft SQL Server 2005 that offers a more readable form of the derived table that can be declared once and referenced multiple times in a query.
We have a simple table Employee
in our database.
Example
;WITH EmployeeCTE AS
( SELECT [EmpID]
,[EmpName]
,[EmpSalary]
FROM [master].[dbo].[Employee]
WHERE [EmpSalary]>4000
)
SELECT * FROM EmployeeCTE
Now press F5 to execute.
Output
Calculating Factorial of Numbers using Common Table Expression
The example of factorial numbers should look as follows:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
The following code defines how to find the factorial of a number:
set nocount on
Declare @Number int,@Fact int
set @Fact=1
set @Number =6; -- To Find Factorial of number
WITH Factorial AS -- Defined Common Table Expression
(
SELECT
CASE WHEN @Number<0 THEN NULL ELSE 1 -- To check if number is 0 it will return 1
END N
UNION all
SELECT (N+1)
FROM Factorial
WHERE N < @Number -- To check factorial number with increment number
)
SELECT @Fact = @Fact*N from Factorial -- To repeat the process
select @Number as 'Number', @Fact as 'Factorial' -- To show result
Print 'The factorial of' +SPACE(1) + cast(@Number as varchar(100)) + SPACE(1) + 'is:' + cast(@Fact as varchar(100)) -- To print a message
Output
When you click on the message tab, the following message will be printed:
Output