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?
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.
Yes, you can alias multiple columns at a time in the same query. It is advisable to always include quotes around the new alias. Quotes are required when the alias contains spaces, punctuation marks, special characters or reserved keywords. It is simply more convenient to always include quotes around the new alias.
SQL aliases are used to give a table, or a column in a table, a temporary name. Aliases are often used to make column names more readable. An alias only exists for the duration of that query. An alias is created with the AS keyword.
SQL Server column alias To assign a column or an expression a temporary name during the query execution, you use a column alias. In this syntax, you use the AS keyword to separate the column name or expression and the alias.
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.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With