Oftentimes there is a need to retrieve different types of the same object (e.g. contacts). For example, in a Contacts database, you might have a Contact table containing many different types of contacts (employees, customers, suppliers, etc). Typically, a user might need to see a report of all different types of contacts for an order (e.g., the customer who placed the order, the employee who took the order, etc.).
Most SQL developers use self-joins to accomplish this, as example 1 in the script window demonstrates (note: I am only using a single table for illustration purposes). Although this does the job, you should know that there is an alternate way to do this (using aggregates and CASE statements) that can often result far fewer scans and better performance, as example 2 below shows.
During my testing while running the graphical showplan, example 2 only required a Compute Scalar and a Clustered Index Scan (I probably could have gotten even better perormance if my company's database had been indexed better). Example 1, however, required 6 Merge Join operations and 7 Index Scans. In addition, example 2 requires far less coding.
While I can't guarantee that this method will result in improved performance in your environment, it's always helpful to now that there is more than one way to perform common programming operations.
Creating a PDF from a Stored Procedure in SQL Server
A short but interesting article, the author has figured out a way to create a PDF from a stored procedure without using a third party library.
2019-09-20 (first published: 2003-08-26)
73,117 reads