Monday, June 02, 2008

Using common table expression in SQL 2005

SQL 2005 has a new feature called Common Table Expression (CTE). You don't need to use table variable any more. It is more powerful. You can use it for recursive query, aggregation query etc.

Ex.

WITH tmp_a (col1, col2, col3)
AS
(
SELECT col1, col2, col3 FROM a WHERE a.flag = 1
)

SELECT * FROM tmp_a
WHERE tmp_a.col1 like 'aa%'