views:

54

answers:

2

I've seen mention of the Oracle WITH clause a few times around here for aliasing a subquery like this:

WITH myData AS (SELECT id, text FROM SomeTable)
SELECT myData from SomeOtherTable

Does any version of SQL Server support this? If not, is there a particular reason they don't? Performance? Potential for incorrect usage?

+4  A: 

Yes SQL2005 and SQL2008 both support this. They are called Common Table Expressions.

Martin Smith
...and a lovely concept to bend your head with when trying to master the recursive CTE!
spender
Yes, but actually the recursive CTE is not that bad once you've written a few. It's way better than the alternatives (such as they are).
harpo
+5  A: 

SQL Server 2005 and up.

I wanted to add that you can stack these to good effect:

WITH A AS (
    SELECT * FROM X
), B AS (
    SELECT * FROM A
), C AS (
    SELECT * FROM B
)
SELECT * FROM C

You can even do:

WITH A AS (
), B AS (
)
SELECT * FROM A INNER JOIN B ON whatever

Also note that WITH must be the first keyword in a statement, so you often see it written as:

;WITH A AS (
)

Which basically terminates the previous statement (semicolons are kind of optional in T-SQL)

Cade Roux
Cool, did not know this!
harpo