Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How we can use CTE in subquery in sql server?

How we can use a CTE in a subquery in SQL Server?

like:

SELECT id (I want to use CTE here), name FROM table_name

like image 853
Paresh Avatar asked Dec 16 '09 11:12

Paresh


People also ask

Can you use CTE in subquery?

¶ A CTE (common table expression) is a named subquery defined in a WITH clause. You can think of the CTE as a temporary view for use in the statement that defines the CTE. The CTE defines the temporary view's name, an optional list of column names, and a query expression (i.e. a SELECT statement).

What is CTE and subquery When will you use CTE and when will you use subquery?

CTE or COMMON TABLE EXPRESSION — a type of temporary data source that houses the results of a query. CTEs are only stored for the duration of a query. SUBQUERY — just like CTEs and temp tables, a subquery is a way to generate a temporary result set to use in a main query.

Is CTE faster than subquery?

As for your question. The performance of CTEs and subqueries should, in theory, be the same since both provide the same information to the query optimizer. One difference is that a CTE used more than once could be easily identified and calculated once. The results could then be stored and read multiple times.


2 Answers

Just define your CTE on top and access it in the subquery?

WITH YourCTE(blubb) AS (     SELECT 'Blubb' ) SELECT id,        (SELECT blubb FROM YourCTE),        name FROM   table_name 
like image 63
Maximilian Mayerl Avatar answered Sep 28 '22 02:09

Maximilian Mayerl


It doesn't work:

select id (I want to use CTE here), name from table_name 

It's not possible to use CTE in sub queries.

You can realize it as a work around:

CREATE VIEW MyCTEView AS ..here comes your CTE-Statement. 

Then you are able to do this:

select id (select id from MyCTEView), name from table_name 
like image 35
Alfred E. Mustermann Avatar answered Sep 28 '22 04:09

Alfred E. Mustermann