Solved

CASE statment in Computed Column Specification

Posted on 2009-06-27
9
1,606 Views
Last Modified: 2012-06-27
Hi..

I have an MS SQL database(SQL SERVER 2005).  I have two columns I want to add together and have no problem doing this in the Computed Column properties with the following.

([itemHandlingPer] + [itemShippingPer])

Now, what if I only want them to add up IF [columnA] = Whatever

I figured I would have to use CASE or something, but I am so new to MS SQL that I cannot seem to figure it out.

Thank You

Tom
0
Comment
Question by:tomhwtt
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
  • +1
9 Comments
 
LVL 23

Expert Comment

by:Racim BOUDJAKDJI
ID: 24727786
First, create a function that takes your aguments as input and do the evaluation within the function.  The typical case formulation is

create function fn_calculatedcolumn5(@itemHandlingPer varchar(10), @itemShippingPer varchar(10))
returns varchar(20)
as
begin
        declare @function_out varchar(20)
        select @function_out =
               case
                   when @itemHandlingPer = '1' then (@itemHandlingPer + @itemShippingPer)
                   when @itemHandlingPer = '2' then @itemHandlingPer
                   else @itemShippingPer
               end
         return @function_out
end

Second, you can declare the function inside the definition of the calculated column.

PS: before adding values don't forget to CAST them explicitely if they re not of the same initial type.  Especially if you store numeric values as varchar.

HTH
0
 

Author Comment

by:tomhwtt
ID: 24727857
Very powerful stuff!  Thank You.

OK..so I have them set as money instead of varchar.

How do I declare the function inside the definition of the calculated column?

Thanks for the quick response!

Tom
0
 
LVL 75

Accepted Solution

by:
Anthony Perkins earned 500 total points
ID: 24727915
Since it is a computed column, I would not resort to using a UDF to do this, but instead just do:

CASE
       WHEN columnA =  Whatever THEN itemHandlingPer + itemShippingPer
        ELSE NULL            -- Or 0 or whatever
END
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 23

Expert Comment

by:Racim BOUDJAKDJI
ID: 24727978
@ Tom
<<OK..so I have them set as money instead of varchar. >>
simply change the varchar to data type money.

<<How do I declare the function inside the definition of the calculated column?>>`here is an example

CREATE TABLE Contact(
      itemHandlingPer            money,
      itemShippingPer      money,
      totalvalue as dbo.fn_calculatedcolumn5(itemHandlingPer, itemShippingPer)
)


@acperkins
<<Since it is a computed column, I would not resort to using a UDF to do this, but instead just do:>>
Is there a specific reason for that?  Functions are specifically designed for encapsulation.

Udf are a nice clean way to keep track of computed columns and formulas.  By default, I think it is a good practice to keep them in functions.  When the number of computed columns increases and it is easier to maintain and encapsulate logic onto.  IMHO
0
 
LVL 75

Expert Comment

by:Anthony Perkins
ID: 24728156
I agree they are a good way to encapsulate logic, however there is overhead involved in scalar UDF's:
Are UDFs Harmful to SQL Server Performance?
http://www.sql-server-performance.com/articles/per/sql_server_udfs_p1.aspx
Proposed Solution to the Performance Problem with SQL Server Scalar UDFs
http://www.novicksoftware.com/Articles/sql-server-udf-performance-problem/sql-server-udf-performance-problem.htm
Performance impact: SQL trace and user defined scalar functions
http://sqlblog.com/blogs/linchi_shea/archive/2009/06/15/performance-impact-sql-trace-and-user-defined-scalar-functions.aspx

So I would argue that unless this same formula is going to be used elsewhere then a simple case is all that is needed.
0
 
LVL 23

Expert Comment

by:Racim BOUDJAKDJI
ID: 24728385
Thanks for the articles you pointed out.  One of them indicates...

<<This penalty shows up as poor query execution time when a query applies a UDF to a large number of rows, typically 1000 or more.  >>>>
In other words, the overhead created by UDF doing few or no IO's does not justifiy discarding them in the context of the current question.  Enpasulating them or not has no performance impact in this case.

<<I agree they are a good way to encapsulate logic>>
That is only *one* good aspect of using them in calculated columns.  Here is another: A function that does not do any IO's from tables (such as in this case) may actually do better caching on heavily accessed columns.   That is not a neglectable advantage.

<<however there is overhead involved in scalar UDF's:>>
These are *general* drawbacks for functions accessing tables and querying them.  My opinion is that, on the *overall* the  cautious use of functions can have strong advantages  in terms of maintainability and  caching.  

But where I agree with you is the fact there is a need to avoid functions that cause heavy IO's. In a sense, functions are a bit like triggers: the fact they can easily get forgotten or do not allow the user to immediately perceive their impact seems to be their main weakness.


Regards...
0
 
LVL 15

Expert Comment

by:rob_farley
ID: 24733077
I wouldn't use a UDF in this scenario. The problem with scalar-UDFs is that it's far too easy for someone to come along and decide that it should look in a table for something, and that can have disastrous effects.

And even if I did, I wouldn't've used @function_out in there... I'd've just returned in directly.

Rob
0
 
LVL 23

Expert Comment

by:Racim BOUDJAKDJI
ID: 24733965
<<he problem with scalar-UDFs is that it's far too easy for someone to come along and decide that it should look in a table for something, and that can have disastrous effects.>>
I understand.  I prefer to thrust my security plan from preventing that from happening.  Somebody who ignores the effect of a specific SQL functionnality should not have access to DDL definitions in the first place.

<<And even if I did, I wouldn't've used @function_out in there... I'd've just returned in directly.>>
Good for you. ;)
0
 

Author Closing Comment

by:tomhwtt
ID: 31597548
Thank You!  Just what I was looking for.
0

Featured Post

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Need help with a query 14 39
SQL Syntax 6 32
SQL question - help with insert for missing info 5 21
How to add an Index to a date/time field? 15 13
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question