Solved

CASE statment in Computed Column Specification

Posted on 2009-06-27
9
1,619 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
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 
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

What Is Transaction Monitoring and who needs it?

Synthetic Transaction Monitoring that you need for the day to day, which ensures your business website keeps running optimally, and that there is no downtime to impact your customer experience.

Question has a verified solution.

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

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
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 combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.

717 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