I need to do something like this but SQL Server 2008 doesn't like it. My query is actually more complex than this and I realize this isn't the best way to accomplish what I'm doing but my focus is on the functionality of the WITH statement and not the select and where statements.
WITH stuff1 AS ( select name, startdate, id from employees where startdate > 0 )
WITH stuff2 AS ( select name, startdate, id from stuff1 )
select * from stuff2 where id > 10
At least if you're running on a SQL Server database, yes it is possible.
SQL filters are text strings that you use to specify a subset of the data items in an internal or SQL database data type. For SQL database and internal data types, the filter is an SQL WHERE clause that provides a set of comparisons that must be true in order for a data item to be returned.
CASE in T-SQL is an expression (not a "statement") - it evaluates to a single, atomic value - and as such, it does not do any data filtering of any kind ....
I do it all the time:
WITH stuff1 AS (
SELECT name
,startdate
,id
FROM employees
WHERE startdate > 0
)
,stuff2 AS (
SELECT name
,startdate
,id
FROM stuff1
)
SELECT *
FROM stuff2
WHERE id > 10
As far as I can tell, I haven't reached a limit in CTEs.
The only thing you can't do (which would be pretty useful) is reuse CTEs in separate SELECT
s:
WITH stuff1 AS (
SELECT name
,startdate
,id
FROM employees
WHERE startdate > 0
)
,stuff2 AS (
SELECT name
,startdate
,id
FROM stuff1
)
SELECT *
FROM stuff2
WHERE id > 10
;
SELECT *
FROM stuff2
WHERE id < 10
Say. Instead you have to copy and paste the entire CTE chain again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With