views:

58

answers:

2

I have a function call in a query, and that result has to be returned with two names.

Example:

SELECT myFunction(column1) as Name1, column2 as Name2 FROM myTable

I want the result of myFunction to be returned in two different columns. Is this possible without making another function call in the column list?

+8  A: 

You can't give a name two aliases directly, but you can repeat a column in a derived query:

SELECT name1, name1 AS name2 FROM 
  (SELECT myFunction(column1) As Name1 From MyTable) base;

You might also simply duplicate the function call. If the function is deterministic then the optimizer may call it just once. (But of course, check the query plan.)

mdma
+1  A: 
SELECT myFunction(column1) as Name1, myFunction(column1) as Name2 FROM myTable

I am guessing this is what you mean. This is often used in a framework that expects a return value and a display value for a drop down list. For example,

select name as DisplayVal, name as ReturnVal from Table
MJB
doesn't it make two function calls to get the same value?
Jenn
@Jenn, yes it does.
Lieven
@Jenn If the function is deterministic, it will be called just once.
Cade Roux