My first introduction to the APPLY operator was using the DMVs. For quite a while after first being introduced, I didn’t understand it or see a use for it. While it is undeniable that it is has some required uses when dealing with table valued functions, it’s other uses evaded me for a while. Luckily, I started seeing some code that used it outside of table valued functions. It finally struck me that it could be used as a replacement for correlated sub queries and derived tables. That’s what we’ll discuss today. I never liked correlated subqueries because it always seemed like adding full blown queries in the select list was confusing and improper. [cc lang=”sql”] SELECT SalesOrderID = soh.SalesOrderID ,OrderDate = soh.OrderDate ,MaxUnitPrice = (SELECT MAX(sod.UnitPrice) FROM Sales.SalesOrderDetail sod WHERE soh.SalesOrderID = sod.SalesOrderID) FROM AdventureWorks.Sales.SalesOrderHeader AS soh [/cc] It always seemed to me that these operations should go below the FROM clause. So to get around this, I would typically create a derived table. Which didn’t completely feel right either, but it was still just a bit cleaner: [cc lang=”sql”] SELECT soh.SalesOrderID ,soh.OrderDate ,sod.max_unit_price FROM AdventureWorks.Sales.SalesOrderHeader AS soh JOIN ( SELECT max_unit_price = MAX(sod.UnitPrice), SalesOrderID FROM Sales.SalesOrderDetail AS sod GROUP BY sod.SalesOrderID ) sod ON sod.SalesOrderID = soh.SalesOrderID [/cc] What made this ugly was the need to use the GROUP BY clause because we could not correlate. Also, even though SQL almost always generates the same execution plan as a correlated sub query, there were times when the logic […]

Continue reading ...

Custom Pagination with Dynamic ORDER BY

SQL Server Denali has a new feature allowing pagination using the order by clause. A common solution needed for the front end is to paginate records prior to sending them to the webserver. More frequently now, we are seeing demormalized data sets being stored in the WebServer’s or a middle tiers cache mechanism. Those solutions however are more difficult to maintain, persist and synchronize. Enter the old fashioned database paging solution. This paging solution initially grabs a subset of a table and counts the records. It then stores ordered results based on the parameter passed into the common table expression. Additional parameters are the number of rows the caller wants on each page and the page number the caller is currently retrieving. [cc lang=”sql”] CREATE PROCEDURE dbo.GetEmployees ( @SortColumn VARCHAR(50) = null, @iRows INT = 10, @iPageNum INT = 1 ) AS BEGIN SET NOCOUNT ON DECLARE @RecordCount int DECLARE @iNbrPages int SET @RecordCount = 0 SET @iNbrPages = 0 SELECT emp.EmployeeID, emp.FirstName, emp.LastName, emp.DateHired INTO #Employees FROM HR.Employees emp WHERE emp.IsTerminated = 1 SELECT @iNbrPages = CEILING(COUNT(1)/(@iRows*1.0)), @RecordCount = COUNT(1) FROM #Employees BEGIN ;WITH PagingCTE ( Row_ID, EmployeeID, FirstName, LastName, DateHired ) AS ( SELECT ROW_NUMBER() OVER(ORDER BY CASE WHEN @SortColumn = ‘EmployeeID’ THEN emp.EmployeeID END ASC, CASE WHEN @SortColumn = ‘FirstName’ THEN emp.FirstName END ASC, CASE WHEN @SortColumn = ‘LastName’ THEN emp.LastName END ASC, CASE WHEN @SortColumn = ‘DateHired’ THEN emp.DateHired END ASC ) AS [Row_ID], emp.EmployeeID, emp.FirstName, emp.LastName, emp.DateHired FROM #Employees emp ) SELECT emp.EmployeeID, emp.FirstName, emp.LastName, […]

Continue reading ...

SQL Server Slow Performance

This post deals with a random hanging that sometimes happens with SQL Server 2005+. In order to troubleshoot SQL Server Slowness, go here. The introduction of the new SQL Server 2005 Query Optimization engine has brought great things (including statement-level caching and smarter execution plan generation). There is however a little more overhead with the advent of this new technology. Aside from taking longer to generate an execution plan, I have noticed two separate instances where a query would appear to intermittently hang. From a database engine perspective however, the query is not hanging but generating an execution plan. The two instances I’ve witnessed this in were in both SQL Server 2005 (sp2), and also now in SQL Server 2008. Both procedures were relatively small, however somewhat complex in their where clauses. The physical indicators in both instances where very high CPU usage and very low IO usage for one particular SPID which we gathered by executing sp_who2. Here is an example of the query that hung on SQL Server 2008: [cc lang=”sql”] SET @IsTrue = ( SELECT COUNT(1) FROM dbo.table1 t1 JOIN dbo.table2 t2 ON t1.ColumnID = t2.ColumnID WHERE ( t2.ID = @ID AND t2.SomeDate < GETDATE() ) OR EXISTS ( SELECT 1 FROM dbo.Table3 WHERE ID = @ID AND AlternateID IN (1,2,3,4,6) ) ) [/cc] Once the query would hang in generating the execution plan, the effect seemed to snowball and cause other executing instances of the same procedure to hang. Also, no blocking was occuring in the […]

Continue reading ...

Featured Articles

 Site Author

  • Thanks for visiting!