views:

111

answers:

1

Hi,

I am trying to perform a simple calculation to some data returned from SQL Server:

SELECT  val1X, val1Y, val2X, val2Y FROM myTable

I want to be able to calculate the following against the returned values and return just a single value - the result of the calculation below (this was originally written in VB6):

 If IsNull(val1X) Or IsEmpty(val1X) Then val1X = 0
    If IsNull(val1Y) Or IsEmpty(val1Y) Then val1Y = 0
    If IsNull(val2X) Or IsEmpty(val2X) Then val2X = 0
    If IsNull(val2Y) Or IsEmpty(val2Y) Then val2Y = 0

    res1 = (val1X ^ 2) + (val1Y ^ 2)
    res2 = (val2X ^ 2) + (val2Y ^ 2)

    ResultVal = Sqr(IIf(res1 > res2, res1, res2))

Just wondering what the best way to do this would be?

Thanks

+3  A: 

You can do it all in one statement in SQL, but it looks kinda ugly because you have to repeat chunks:

SELECT 
  CASE WHEN 
    /* res1 */ Power(IsNull(val1X, 0), 2) + Power(IsNull(val1Y, 0), 2) 
    > /* res2 */ Power(IsNull(val2X, 0), 2) + Power(IsNull(val2Y, 0), 2)
  THEN
    /* res1 */ Power(IsNull(val1X, 0), 2) + Power(IsNull(val1Y, 0), 2)
  ELSE
    /* res2 */ Power(IsNull(val2X, 0), 2) + Power(IsNull(val2Y, 0), 2)
  END
FROM
  myTable

It'd be a little cleaner to use a user-defined function to wrap up that Power(IsNull(field, 0), 2) so you don't repeat yourself as much, but I'll leave that as an exercise for you to do. :)

Ian Varley
that's excellent, thanks. Just one last question, how do I specify the column name for this?
Belliez
solved, I just used the "AS columnname" at the end of the SELECT statement.
Belliez