Solved

CASE statment in Computed Column Specification

Posted on 2009-06-27
9
1,576 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
  • 4
  • 2
  • 2
  • +1
9 Comments
 
LVL 23

Expert Comment

by:Racim BOUDJAKDJI
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 23

Expert Comment

by:Racim BOUDJAKDJI
Comment Utility
@ 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
Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

 
LVL 75

Expert Comment

by:Anthony Perkins
Comment Utility
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
Comment Utility
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 14

Expert Comment

by:rob_farley
Comment Utility
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
Comment Utility
<<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
Comment Utility
Thank You!  Just what I was looking for.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Let's review the features of new SQL Server 2012 (Denali CTP3). It listed as below: PERCENT_RANK(): PERCENT_RANK() function will returns the percentage value of rank of the values among its group. PERCENT_RANK() function value always in be…
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties

744 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now