In Common Table Expression we
can create a recursive query. Reference the resulting table multiple times in
the same statement. CTEs can be defined in user-defined routines, such as
functions, stored procedures, triggers, or views.
EXAMPLE : 1
UPDATE or SELECT single row from a table which has many realted duplicates row
WITH CTE (config_element, rowNum)
AS
(
SELECT
config_element,
ROW_NUMBER() OVER(PARTITION BY
config_element ORDER BY
config_element) AS
rowNum
FROM [myDb].[dbo].[temp_configuration]
)
--UPDATE CTE SET
config_element='factoryShortKeys' WHERE rowNum=2
SELECT * from CTE WHERE rowNum = 2
GO
EXAMPLE : 2
Using multiple CTE in single select query
WITH CTE_test1 AS (SELECT 100 AS Col1),
CTE_test2 AS (SELECT COL1+1 AS Col2 FROM
CTE_test1)
SELECT CTE_test1.Col1, CTE_test2.Col2 FROM
CTE_test1
CROSS JOIN CTE_test2
GO
EXAMPLE : 3
Using multiple CTE in single select query
WITH
CTE_test1 AS (SELECT 100 AS Col1),
CTE_test2 AS (SELECT COL1+1 AS Col2 FROM
CTE_test1)
SELECT CTE_test1.Col1, CTE_test2.Col2 FROM
CTE_test1
CROSS JOIN CTE_test2
GO
For further detail see link:
No comments:
Post a Comment