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
Senior Java Software Engineer | Kotlin | Spring Boot | React | Angular | AWS | Docker | Kubernetes | TypeScript | FullStack
2moVery good, man. It's a very useful command
Senior React Developer | Full Stack Developer | JavaScript | TypeScript | Node.js
2moNice, thanks for sharing !
Software Engineer Fullstack | Java | Angular
2moGorgeous 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!
Senior Software Engineer | Java | Spring | AWS
2moGreat 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!
AI Consultant, Tech Lead, Full Stack Developer and Co-Founder
2moI like using cross apply with function tables