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 Java Software Engineer | Kotlin | Spring Boot | React | Angular | AWS | Docker | Kubernetes | TypeScript | FullStack

2mo

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

Bruno Freitas

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

2mo

Nice, thanks for sharing !

Gilberto Melo

Software Engineer Fullstack | Java | Angular

2mo

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

2mo

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

2mo

I like using cross apply with function tables

To view or add a comment, sign in

More articles by Cassio Almeron

  • Unit Tests Over Protected and Private Methods

    By definition, it is not possible to access externally private or protected methods. And there are design reasons for…

    9 Comments
  • Entity Framework: In Memory for Automated Tests.

    I’ve been studying EF Core, specifically following the course “Entity Framework Core - A Full Tour” by Trevoir Williams…

    9 Comments
  • TDD Over Databases

    I don’t know how many systems are still working with its core implemented inside the database, but I believe it is not…

    6 Comments
  • Strategy Pattern for TDD

    Well, applying TDD over simple and isolated methods is something quite simple. This example below is a simple…

    9 Comments
  • System.Lazy in C#

    During a work task, I was asked to manage the loading of an object just once in its first usage. It is something that I…

    8 Comments
  • The Misconception of Forgiveness in Portuguese.

    A few times ago, I read the book “The 6 Phase of Meditation Method” by Vishen Lakhiani, which abords the concepts and…

    1 Comment

Insights from the community

Others also viewed

Explore topics