Reuse query statements in SQL with Cross Apply

Reuse query statements in SQL with Cross Apply

Have you ever had a situation where you needed to repeat code in an SQL command?

I had many times, and I used to copy and paste the code snipped.

As a consequence, every time a change or a fix needs to be made, it is necessary to be careful and remember to change all the places where it was replicated.

Here is an example: the subtotal is a calculated field, and it is also being used in the where clause

Select I.Quantity * I.Price as SubTotal
from InvoiceItem I
where I.Quantity * I.Price > 100        

Here is the same query, with the calculation centered in a cross-apply:

Select Calc.SubTotal
from InvoiceItem I
cross apply (
	select I.Quantity * I.Price as SubTotal
) Calc
where Calc.SubTotal > 100
        
Edmar Fagundes

Senior Software Engineer | FullStack Developer | Java | Kotlin | Node | Spring Boot | React | Angular | Next | AWS | Docker | Kubernetes | TypeScript

5mo

Very good, man. It's a very useful command

Bruno Freitas

Senior React Developer | Full Stack Developer | JavaScript | TypeScript | Node.js

5mo

Nice, thanks for sharing !

Gilberto Melo

Senior Software Engineer Fullstack | Java | Angular

5mo

Gorgeous tip! I have searched for something like it since I began my journey as a developer and finally I have what can help me. Thanks a lot my friend!

Fabio Ribeiro

Senior Software Engineer | Java | Spring | AWS

5mo

Great tip, Cassio! I've found cross-apply to be incredibly useful for reusing statements in complex queries. Do you have any specific scenarios where you've seen it shine? Would love to hear more about your experiences!

Bernardo Dal Corno

AI Consultant, Tech Lead, Full Stack Developer and Co-Founder

5mo

I like using cross apply with function tables

To view or add a comment, sign in

Others also viewed

Explore topics