Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use WITH in TSQL twice to filter a result set like my example?

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

like image 837
Paul Mendoza Avatar asked Jan 28 '09 19:01

Paul Mendoza


People also ask

Can we use with twice in SQL?

At least if you're running on a SQL Server database, yes it is possible.

How do you subset or filter data in SQL explain with example?

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.

Which statement would you not use to filter data in SQL?

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 ....


1 Answers

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 SELECTs:

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.

like image 122
Cade Roux Avatar answered Oct 15 '22 15:10

Cade Roux