Quantcast
Channel: T-SQL: Simplified CASE expression
Viewing all articles
Browse latest Browse all 43

Simplified CASE expression

$
0
0
Revision 12 posted to TechNet Articles by Saeid Hasani on 12/3/2013 9:19:14 AM


Introduction

SQL Server 2012 introduces these two new functions which simplify CASE expression:

  • Conditional function ( IIF)
  • Selection function ( CHOOSE )

Also we have been working with COALESCE, an old simplified CASE expression statement as NULL related statement prior SQL Server 2012. Although ISNULL is a function which logically simplifies a CASE expression, but it never translates to a CASE expression behind the scene (by execution plan). By the way, we will also cover ISNULL in this article, since it’s an alternative to COALESCE. The goal of this article is providing an in depth tutorial about these four statements:

  1. ISNULL
  2. COALESCE
  3. IIF
  4. CHOOSE

I use the term “statement” because although they do similar duty but they are not in same category by their purpose. For example ISNULL is a function while COALESCE is an expression.

As we will see later, the main purpose of introducing these statements are improving code readability and simplifying maintenance of code. But in some situations these statements usage will lead to poor performance. So we also will discuss about some alternative solutions.

This article targets newbies to advanced audiences. So if you are familiar with these statements, you can skip definition section.

Definition

ISNULL

ISNULL(expr_1, expr_2)

If expr_1 is null, then ISNULL function returns expr_2, otherwise returns expr_1. Following example shows its functionality.

DECLARE@expr_1 NVARCHAR(10) ,
        @expr_2 NVARCHAR(10) ;
 
SET@expr_1 = NULL;
SET@expr_2 = N'Saeid';
 
SELECT@expr_1 ASexpr_1,
       @expr_2AS expr_2,
       ISNULL(@expr_1, @expr_2)AS [ISNULLResult]


Pic 001


If the data types of two arguments are different, if they areimplicitly convertible SQL Server converts one to the other, otherwise returns an error. Next sample execution leads to an error as illustrated in output figure.

DECLARE@Val_1 INT,
        @Val_2 NVARCHAR(10) ;
 
SET@Val_1 = NULL;
SET@Val_2 = 'Saeid';
 
SELECT@Val_1 AS[Value 1],
       @Val_2AS [Value 2],
       ISNULL(@Val_1, @Val_2)AS [ISNULLResult]

Pic 002

Whereas by changing the value of the variable @Val_2 to ‘500’, because this value is convertible to numeric data type INT, we do not encounter any error. Following code demonstrate this:  

DECLARE@Val_1 INT,
        @Val_2 NVARCHAR(10) ;
         
SET@Val_1 = NULL;
SET@Val_2 = '500';
 
SELECT@Val_1 AS[Value 1],
       @Val_2AS [Value 2],
       ISNULL(@Val_1, @Val_2)AS [ISNULLResult]

Pic 003

Implicit conversion in ISNULL function also could lead to truncate value, if the length of expr_1 data typeis smaller than length of expr_2 data type. So it’s safer to convert explicitly if needed. In next example first SELECT list column suffers from value truncation while second will not.

DECLARE@Val_1 NVARCHAR(2) ,
        @Val_2 NVARCHAR(10) ;
 
SET@Val_1 = NULL;
SET@Val_2 = 'Saeid';
 
SELECTISNULL(@Val_1, @Val_2)AS [ISNULLResult],
       ISNULL(CONVERT(NVARCHAR(10), @Val_1), @Val_2) AS [ISNULLResultwith explicit convert]

Pic 004


Determine output data type

The next code illustrates the rules to determine output data type:

IF OBJECT_ID('dbo.TestISNULL','U') ISNOTNULL
  DROPTABLE dbo.TestISNULL ;
 
DECLARE@Val_1 NVARCHAR(200) ,
        @Val_2 DATETIME ;
 
SET@Val_1 = NULL;
SET@Val_2 = GETDATE() ;
 
SELECTISNULL('Saeid', @Val_2)AS Col1,
       ISNULL(@Val_1, @Val_2)AS Col2,
       ISNULL(NULL, @Val_2)AS Col3,
       ISNULL(NULL,NULL) AS Col4     
INTOdbo.TestISNULL
WHERE1 = 0 ;
GO
 
SELECTCOLUMN_NAME ,
       DATA_TYPE ,
       CHARACTER_MAXIMUM_LENGTH
FROMINFORMATION_SCHEMA.COLUMNS
WHERETABLE_SCHEMA = N'dbo'
  ANDTABLE_NAME = N'TestISNULL';

Pic 005


Determine output NULL-ability

The next code illustrates the rules to determine output data type:

IF OBJECT_ID('dbo.TestISNULL','U') ISNOTNULL
  DROPTABLE dbo.TestISNULL ;
 
DECLARE@Val_1 NVARCHAR(200) ,
        @Val_2 DATETIME ;
 
SET@Val_1 = NULL;
SET@Val_2 = GETDATE() ;
 
SELECTISNULL('Saeid', @Val_2)AS Col1,
       ISNULL(@Val_1, @Val_2)AS Col2 
INTOdbo.TestISNULL
WHERE1 = 0 ;
GO
 
SELECTCOLUMN_NAME ,
       IS_NULLABLE
FROMINFORMATION_SCHEMA.COLUMNS
WHERETABLE_SCHEMA = N'dbo'
  ANDTABLE_NAME = N'TestISNULL';

Pic 006



COALESCE 

COALESCE(expr_1, expr_2, ..., expr_n)       --for n >=2

COALESCE returns the first NOT NULL expr in the expression list. It needs at least two expressions.

Dissimilar from ISNULL function, COALESCE is not a function, rather it’s an expression. COALESCE always translates to CASE expression. For example,

COALESCE (expr_1, expr_2)

is equivalent to:

CASE

WHEN (expr_1 IS NOT NULL) THEN (expr_1)

ELSE (expr_2)

END

Therefore the database engine handles it like handling CASE expression. So this is in our simplified CASE expression list.

Following code is one of many samples that could illustrate different execution plans for COALESCE and ISNULL:

USE AdventureWorks2012 ;
GO
 
SELECT*
FROMSales.SalesOrderDetail
WHEREISNULL(ProductID, SpecialOfferID) = 3
 
 
SELECT*
FROMSales.SalesOrderDetail
WHEREcoalesce(ProductID, SpecialOfferID) = 3

Pic 007

By using COALESCE, we do not have the limitations that discussed about ISNULL function, neither about output data type nor output column NULL-ability. Even there is not suffering from value truncation. To illustrate these points, next example is the new revision of former examples that was provided for ISNULL, but replace with COALESCE:

-- value truncation
DECLARE@Val_1 NVARCHAR(2) ,
        @Val_2 NVARCHAR(10) ;
 
SET@Val_1 = NULL;
SET@Val_2 = 'Saeid';
 
SELECTISNULL(@Val_1, @Val_2)AS [ISNULLResult],
       ISNULL(CONVERT(NVARCHAR(10), @Val_1), @Val_2) AS [ISNULLResultwith explicit convert],
       COALESCE(@Val_1, @Val_2)AS [COALESCEResult]
GO
 
----------------------------------------------------------
-- output data type
IF OBJECT_ID('dbo.TestISNULL','U') ISNOTNULL
  DROPTABLE dbo.TestISNULL ;
 
DECLARE@Val_1 NVARCHAR(200) ,
        @Val_2 DATETIME ;
 
SET@Val_1 = NULL;
SET@Val_2 = GETDATE() ;
 
SELECTCOALESCE('Saeid', @Val_2)AS Col1,
       COALESCE(@Val_1, @Val_2)AS Col2,
       COALESCE(NULL, @Val_2)AS Col3
INTOdbo.TestISNULL
WHERE1 = 0 ;
GO
 
SELECTCOLUMN_NAME ,
       DATA_TYPE ,
       CHARACTER_MAXIMUM_LENGTH
FROMINFORMATION_SCHEMA.COLUMNS
WHERETABLE_SCHEMA = N'dbo'
  ANDTABLE_NAME = N'TestISNULL';
GO
 
----------------------------------------------------------
-- NULL-ability
IF OBJECT_ID('dbo.TestISNULL','U') ISNOTNULL
  DROPTABLE dbo.TestISNULL ;
 
DECLARE@Val_1 NVARCHAR(200) ,
        @Val_2 DATETIME ;
 
SET@Val_1 = NULL;
SET@Val_2 = GETDATE() ;
 
SELECTCOALESCE('Saeid', @Val_2)AS Col1,
       COALESCE(@Val_1, @Val_2)AS Col2 
INTOdbo.TestISNULL
WHERE1 = 0 ;
GO
 
SELECTCOLUMN_NAME ,
       IS_NULLABLE
FROMINFORMATION_SCHEMA.COLUMNS
WHERETABLE_SCHEMA = N'dbo'
  ANDTABLE_NAME = N'TestISNULL';
GO

Pic 008

IIF

IIF( condition , x, y)

IIF is a logical function which introduced in SQL Server 2012. It’s like conditional operator in C-Sharp language. If condition is true, x evaluated, else y evaluated. Following example illustrates this:

DECLARE@x NVARCHAR(10) ,
        @y NVARCHAR(10) ;
 
SET@x = N'True' ;
SET@y = N'False' ;
 
SELECTIIF( 1 = 0, @x, @y) AS[IIF Result]

Pic 009

Like COALESCE expression, IIF function always translates to CASE expression. For instance,

IIF ( condition, true_value, false_value )

is equivalent to:

Case

when  (condition is true) then (true_value)

Else (false_value)

End

This example shows that this translation.

USE AdventureWorks2012 ;
GO
 
SELECT*
FROMSales.SalesOrderDetail
WHEREIIF ( OrderQty >= SpecialOfferID , OrderQty, SpecialOfferID ) = 1

Pic 010


CHOOSE
 

CHOOSE(index, val_1, val_2, ..., val_n)     --for n >=1

CHOOSE is a selection function which introduced in SQL Server 2012. It’s like switch operator in C-Sharp language. If index (must be convertible to data type INT) is NULL or its value is not found, output will be NULL. This function needs at least two arguments, one for index and other for value. Following code illustrates this:

DECLARE@indexINT ;
 
SET@index= 2 ;
 
SELECTCHOOSE(@index,'Black', 'White', 'Green')

Pic 011

Like COALESCE expression and IIF function, CHOOSE also always translates to CASE expression. For example,

CHOOSE ( index, val_1, val_2 )

is equivalent to:

Case

when  (index = 1) then val_1

when  (index = 2) then val_2

Else NULL

End

This simple code shows that this translation.

USE AdventureWorks2012 ;
GO
 
SELECT*
FROMSales.SalesOrderDetail
WHERECHOOSE(OrderQty, 'Black','White', 'Green') = 'White'

Pic 012



Performance

Although the main purpose of simplified CASE expression statements is increasing readability and having cleaner codes, but one important question is how these statements impact on the database performance. Does any performance different between CASE expression and these statements? In this path we will be noticed that to achieve best performance it’s usually better to find alternative solutions to avoid using CASE and these statements.

Dynamic filtering

This is common to write reports and searches which accept input parameters. To achieve better performance it’s a good practice to write their code within stored procedures, because procedures store the way of their executing as an execution plan and reuse it again. By the way, there are some popular solutions to do this.

IS NULL and OR

This is the most common solution. Let me start with an example and rewrite it with comparable solutions:

USE AdventureWorks2012;
GO
IF OBJECT_ID('Sales.SalesOrderDetailSearch','P') ISNOTNULL
  DROPPROC Sales.SalesOrderDetailSearch ;
GO
CREATEPROC Sales.SalesOrderDetailSearch
    @ModifiedDateAS DATETIME = NULL ,
    @ShipDateAS DATETIME = NULL ,
    @StoreIDAS INT= NULL
AS
    SELECT b.ShipDate ,
            c.StoreID ,
            a.UnitPriceDiscount ,
            b.RevisionNumber ,
            b.DueDate ,
            b.ShipDate ,
            b.PurchaseOrderNumber ,
            b.TaxAmt ,
            c.PersonID ,
            c.AccountNumber ,
            c.StoreID
    FROM   Sales.SalesOrderDetail a
    RIGHTOUTERJOIN Sales.SalesOrderHeader b ONa.SalesOrderID = b.SalesOrderID
    LEFTOUTERJOIN Sales.Customer c ON b.CustomerID = c.CustomerID
    WHERE  (a.ModifiedDate = @ModifiedDate OR@ModifiedDate ISNULL)
            AND(b.ShipDate = @ShipDate OR@ShipDate ISNULL)
            AND(c.StoreID = @StoreID OR@StoreID ISNULL)
GO
 
-----------------------------------------------
-- now execute it with sample values
EXECSales.SalesOrderDetailSearch @ModifiedDate = '2008-04-30 00:00:00.000'
EXECSales.SalesOrderDetailSearch @ShipDate = '2008-04-30 00:00:00.000'
EXECSales.SalesOrderDetailSearch @StoreID = 602

Pic 013

The main problem here as illustrated in above figure is using same execution plan for all three situation. It’s obvious that third one suffers from an inefficient execution plan.

CASE

We can change the combination of IS NULL and OR and translate it using CASE for conditions in WHERE clause. Now we rewrite above code like this one:

USE AdventureWorks2012;
GO
IF OBJECT_ID('Sales.SalesOrderDetailSearch','P') ISNOTNULL
  DROPPROC Sales.SalesOrderDetailSearch ;
GO
CREATEPROC Sales.SalesOrderDetailSearch
    @ModifiedDateAS DATETIME = NULL ,
    @ShipDateAS DATETIME = NULL ,
    @StoreIDAS INT= NULL
AS
    SELECT b.ShipDate ,
            c.StoreID ,
            a.UnitPriceDiscount ,
            b.RevisionNumber ,
            b.DueDate ,
            b.ShipDate ,
            b.PurchaseOrderNumber ,
            b.TaxAmt ,
            c.PersonID ,
            c.AccountNumber ,
            c.StoreID
    FROM   Sales.SalesOrderDetail a
    RIGHTOUTERJOIN Sales.SalesOrderHeader b ONa.SalesOrderID = b.SalesOrderID
    LEFTOUTERJOIN Sales.Customer c ON b.CustomerID = c.CustomerID
    WHERE  a.ModifiedDate = CASEWHEN @ModifiedDate IS NOTNULL THEN@ModifiedDate ELSEa.ModifiedDate END
            ANDb.ShipDate = CASEWHEN @ShipDate IS NOTNULL THEN@ShipDate ELSEb.ShipDate END
            ANDc.StoreID = CASEWHEN @StoreID IS NOTNULL THEN@StoreID ELSEc.StoreID END
GO
-----------------------------------------------
-- now execute it with sample values
EXECSales.SalesOrderDetailSearch @ModifiedDate = '2008-04-30 00:00:00.000'
EXECSales.SalesOrderDetailSearch @ShipDate = '2008-04-30 00:00:00.000'
EXECSales.SalesOrderDetailSearch @StoreID = 602

Pic 014

Using CASE shows improvements to IS NULL and OR, but with more CPU cost for first one. Also the Reads and Actual Rows decreased in first two executions. So it’s better but still we continue this experiment.

COALESCE

We can change CASE and translate it to COALESCE for conditions in WHERE clause. Now we rewrite above code like this:

USE AdventureWorks2012;
GO
IF OBJECT_ID('Sales.SalesOrderDetailSearch','P') ISNOTNULL
  DROPPROC Sales.SalesOrderDetailSearch ;
GO
CREATEPROC Sales.SalesOrderDetailSearch
    @ModifiedDateAS DATETIME = NULL ,
    @ShipDateAS DATETIME = NULL ,
    @StoreIDAS INT= NULL
AS
    SELECT b.ShipDate ,
            c.StoreID ,
            a.UnitPriceDiscount ,
            b.RevisionNumber ,
            b.DueDate ,
            b.ShipDate ,
            b.PurchaseOrderNumber ,
            b.TaxAmt ,
            c.PersonID ,
            c.AccountNumber ,
            c.StoreID
    FROM   Sales.SalesOrderDetail a
    RIGHTOUTERJOIN Sales.SalesOrderHeader b ONa.SalesOrderID = b.SalesOrderID
    LEFTOUTERJOIN Sales.Customer c ON b.CustomerID = c.CustomerID
    WHERE  a.ModifiedDate = COALESCE(@ModifiedDate, a.ModifiedDate)
            ANDb.ShipDate = COALESCE(@ShipDate, b.ShipDate)
            ANDc.StoreID = COALESCE(@StoreID, c.StoreID)
GO
 
-----------------------------------------------
-- now execute it with sample values
EXECSales.SalesOrderDetailSearch @ModifiedDate = '2008-04-30 00:00:00.000'
EXECSales.SalesOrderDetailSearch @ShipDate = '2008-04-30 00:00:00.000'
EXECSales.SalesOrderDetailSearch @StoreID = 602

Pic 015

It’s obvious that because COALESCE translates to CASE internally, so there is no different between them.

ISNULL

Now we rewrite above code and use ISNULL instead of COALESCE:

USE AdventureWorks2012;
GO
IF OBJECT_ID('Sales.SalesOrderDetailSearch','P') ISNOTNULL
  DROPPROC Sales.SalesOrderDetailSearch ;
GO
CREATEPROC Sales.SalesOrderDetailSearch
    @ModifiedDateAS DATETIME = NULL ,
    @ShipDateAS DATETIME = NULL ,
    @StoreIDAS INT= NULL
AS
    SELECT b.ShipDate ,
            c.StoreID ,
            a.UnitPriceDiscount ,
            b.RevisionNumber ,
            b.DueDate ,
            b.ShipDate ,
            b.PurchaseOrderNumber ,
            b.TaxAmt ,
            c.PersonID ,
            c.AccountNumber ,
            c.StoreID
    FROM   Sales.SalesOrderDetail a
    RIGHTOUTERJOIN Sales.SalesOrderHeader b ONa.SalesOrderID = b.SalesOrderID
    LEFTOUTERJOIN Sales.Customer c ON b.CustomerID = c.CustomerID
    WHERE  a.ModifiedDate = ISNULL(@ModifiedDate, a.ModifiedDate)
            ANDb.ShipDate = ISNULL(@ShipDate, b.ShipDate)
            ANDc.StoreID = ISNULL(@StoreID, c.StoreID)
GO
-----------------------------------------------
-- now execute it with sample values
EXECSales.SalesOrderDetailSearch @ModifiedDate = '2008-04-30 00:00:00.000'
EXECSales.SalesOrderDetailSearch @ShipDate = '2008-04-30 00:00:00.000'
EXECSales.SalesOrderDetailSearch @StoreID = 602

Pic 016

There is no difference in Durations, but with more estimated rows.

Dynamic SQL

Using above four solutions we never achieve better performance, because we need different efficient execution plans for each combination of input parameters. So it’s time to use alternative solution to overcome this problem.

USE AdventureWorks2012;
GO
IF OBJECT_ID('Sales.SalesOrderDetailSearch','P') ISNOTNULL
  DROPPROC Sales.SalesOrderDetailSearch ;
GO
CREATEPROC Sales.SalesOrderDetailSearch
    @ModifiedDateAS DATETIME = NULL ,
    @ShipDateAS DATETIME = NULL ,
    @StoreIDAS INT= NULL
AS
DECLARE@sql NVARCHAR(MAX), @parameters NVARCHAR(4000) ;
 
SET@sql = '
    SELECT  b.ShipDate ,
            c.StoreID ,
            a.UnitPriceDiscount ,
            b.RevisionNumber ,
            b.DueDate ,
            b.ShipDate ,
            b.PurchaseOrderNumber ,
            b.TaxAmt ,
            c.PersonID ,
            c.AccountNumber ,
            c.StoreID
    FROM    Sales.SalesOrderDetail a
    RIGHT OUTER JOIN Sales.SalesOrderHeader b ON a.SalesOrderID = b.SalesOrderID
    LEFT OUTER JOIN Sales.Customer c ON b.CustomerID = c.CustomerID
    WHERE   1 = 1 '
    IF @ModifiedDateIS NOTNULL
        SET@sql = @sql + ' AND a.ModifiedDate = @xModifiedDate '
    IF @ShipDateIS NOTNULL
        SET@sql = @sql + ' AND OrderQty = @xShipDate '
    IF @StoreIDIS NOTNULL
        SET@sql = @sql + ' AND ProductID = @xStoreID '
 
SET@parameters =
'@xModifiedDate AS DATETIME ,
 @xShipDate AS DATETIME ,
 @xStoreID AS INT';
 
EXECsp_executesql @sql, @parameters,
                   @ModifiedDate, @ShipDate, @StoreID ;
 
GO
 
-----------------------------------------------
-- now execute it with sample values
EXECSales.SalesOrderDetailSearch @ModifiedDate = '2008-04-30 00:00:00.000'
EXECSales.SalesOrderDetailSearch @ShipDate = '2008-04-30 00:00:00.000'
EXECSales.SalesOrderDetailSearch @StoreID = 602

Pic 017

There is no doubt that this solution is the best one!

You can find more information about last solution inErland Sommarskog website.


Concatenate values in one column

This is another common problem that fits to our discussion. In this example we just cover COALESCE and ISNULL solutions and at last we will see an alternative solution which performs better than using the CASE solutions.

COALESCE

Next code concatenates the values of column “ProductID” and delimited each with comma separator.

USE AdventureWorks2012
GO
DECLARE@sql NVARCHAR(MAX);
 
SELECT@sql = COALESCE(@sql +', ', '') +CONVERT(NVARCHAR(100), ProductID)
FROMSales.SalesOrderDetail
WHERESalesOrderID < 53000

Pic 018

This code executed in 13 seconds in our test system.

ISNULL

Now we rewrite above code and use ISNULL instead of COALESCE:

USE AdventureWorks2012
GO
DECLARE@sql NVARCHAR(MAX);
 
SELECT@sql = ISNULL(@sql +', ', '') +CONVERT(NVARCHAR(100), ProductID)
FROMSales.SalesOrderDetail
WHERESalesOrderID < 53000

Pic 019 
                                                                        

The duration decreased to 3 seconds.

XML

It’s time to use alternative solution to overcome this problem.

USE AdventureWorks2012
GO
DECLARE@sql NVARCHAR(MAX);
 
SELECT @sql = ( SELECTSTUFF(( SELECT ','+ CONVERT(NVARCHAR(100), ProductID)AS [text()]
                                FROM   Sales.SalesOrderDetail
                                WHERE  SalesOrderID < 53000
                              FOR
                                XML PATH('')
                              ), 1, 1,'')
               ) ;

Pic 020

The duration decreased to 21 milliseconds.

There is no doubt that this solution is the best one. But because using XML, this solution has some limitations related to some special characters.  


Branch program execution based on switch between possible values

This is so common to use CHOOSE function to write cleaner codes. But is it the best solution to achieve optimal performance? In this section we discuss about this question.

CHOOSE

Let’s start with an example that uses CHOOSE as its solution.

USE AdventureWorks2012 ;
GO
 
SELECT*
FROMSales.SalesOrderDetail
WHERECHOOSE(OrderQty, 'J','I', 'H','G', 'F','E', 'D','C', 'B','A')
        IN( 'J','Q', 'H','G', 'X','E', 'D','Y', 'B','A', NULL)
 
GO

Pic 021

This code executed in 352 milliseconds in our test system.

UDF function

Now we rewrite above code and use a Table Valued Function to produce CHOOSE list:

USE AdventureWorks2012 ;
GO
 
CREATEFUNCTION ufnLookup ()
RETURNSTABLE
AS
RETURN
    SELECT1 ASIndexer, 'J' ASval
    UNIONALL
    SELECT2, 'I'
    UNIONALL
    SELECT3, 'H'
    UNIONALL
    SELECT4, 'G'
    UNIONALL
    SELECT5, 'F'
    UNIONALL
    SELECT6, 'E'
    UNIONALL
    SELECT7, 'D'
    UNIONALL
    SELECT8, 'C'
    UNIONALL
    SELECT9, 'B'
    UNIONALL
    SELECT10, 'A'
 
GO
 
SELECT*
FROMSales.SalesOrderDetail a
JOINdbo.ufnLookup() b ONa.OrderQty = b.Indexer
WHEREb.val IN ( 'J', 'Q', 'H','G', 'X','E', 'D','Y', 'B','A', NULL) ;

Pic 022   
                                                                      

The duration decreased to 195 milliseconds.

Permanent Lookup Table

It’s time to use alternative solution to overcome this problem.

USE AdventureWorks2012 ;
GO
 
CREATETABLE LookupTable
( idINT PRIMARYKEY, valCHAR(1) ) ;
GO
 
INSERTdbo.LookupTable
        ( id, val )
    SELECT1 ASIndexer, 'J' ASval
    UNIONALL
    SELECT2, 'I'
    UNIONALL
    SELECT3, 'H'
    UNIONALL
    SELECT4, 'G'
    UNIONALL
    SELECT5, 'F'
    UNIONALL
    SELECT6, 'E'
    UNIONALL
    SELECT7, 'D'
    UNIONALL
    SELECT8, 'C'
    UNIONALL
    SELECT9, 'B'
    UNIONALL
    SELECT10, 'A' ;
GO
 
SELECT*
FROMSales.SalesOrderDetail a
JOINdbo.LookupTable b ONa.OrderQty = b.Id
WHEREb.val IN ( 'J', 'Q', 'H','G', 'X','E', 'D','Y', 'B','A', NULL)

Pic 023

The duration decreased to 173 milliseconds.

This solution is the best one. By increasing the number of values in parameter list of CHOOSE function, the performance decreases. So by using permanent lockup table that benefits from physical index we can achieve the best performance.


More Readability


The most important goal to use these simplified CASE statements is achieve cleaner code. Many times we encounter this issue that code is so large that the SELECT list becomes more than hundred lines. Therefore this is a significant reason to use these statements. I encountered simple problem just few years ago. In first sight it seems that solution should be very simple. After writing the code using CASE, I found I am in trouble. The problem was simple. Assume that a department store has two discount plan, one based on purchases amount, and other based on the distance from customer’s home to store. But the rule was that just one plan that is greater is applicable. Next code shows it:

IF OBJECT_ID('tempdb..#temp','U') ISNOTNULL
  DROPTABLE #temp ;
CREATETABLE #temp ( CustomerId INT, Bill MONEY, DistanceINT ) ;
INSERT#temp
        ( CustomerId, Bill, Distance )
VALUES( 1, 30.00, 3 ),
       ( 2, 10.00, 8 ),
       ( 3, 5.00, 14 ),
       ( 4, 20.00, 21 ),
       ( 5, 25.00, 23 ),
       ( 6, 5.00, 27 ) ;
 
SELECT*
FROM#temp
 
-- solution using CASE
SELECT
       CASE
         WHEN
           CASEWHEN Bill < 10.00 THEN 10 ELSE 20 END> CASE WHENDistance < 10 THEN7 ELSE13 END
             THENCASE WHENBill < 10.00 THEN10 ELSE20 END
         ELSECASE WHENDistance < 10 THEN7 ELSE13 END
       ENDAS Discount
FROM#temp
 
--solution using IIF
SELECT
      IIF( IIF( Bill < 10.00 , 10 ,20 ) > IIF( Distance < 10 , 7 , 13 )
          ,IIF( Bill < 10.00 , 10 ,20 ) , IIF( Distance < 10 , 7 , 13 ) )AS Discount
FROM#temp




Conclusion

Although using simplified CASE expression statement leads to have cleaner code and speed up development time, they show poor performance in some situations. So if we are in performance tuning phase of software development, it’s better to think about some alternative solutions. 





See Also 




Tags: SQL Server, In progress, has code, has image, en-US, has comment, has See Also, TechNet Guru

Viewing all articles
Browse latest Browse all 43

Trending Articles