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

1 个月

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

Bruno Freitas

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

1 个月

Nice, thanks for sharing !

Gilberto Melo

Software Engineer Fullstack | Java | Angular | AWS

1 个月

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

1 个月

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

1 个月

I like using cross apply with function tables

要查看或添加评论,请登录

Cassio Almeron的更多文章

  • TDD Over Databases

    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 条评论
  • Strategy Pattern for TDD

    Strategy Pattern for TDD

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

    9 条评论
  • System.Lazy in C#

    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 条评论
  • The Misconception of Forgiveness in Portuguese.

    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 条评论

社区洞察

其他会员也浏览了