SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Using Coalesce to assign value to variable?
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Eagle_f90
Constraint Violating Yak Guru

USA
419 Posts

Posted - 08/14/2013 :  11:05:08  Show Profile  Visit Eagle_f90's Homepage  Reply with Quote
I would like to assign the value of 1 of 2 columns (Col1, Col2) in my table to a variable (@var) depending on if Col1 value is NULL or not. If Col1 is NULL I want the value in Col2 to be assigned, if Col1 has a value I want it assigned. I was thinking of using Coalesce as I have used it before to check for null in two variables but I am not sure if/how to use it in a select statement to assign the needed value to the variable.

--
If I get used to envying others...
Those things about my self I pride will slowly fade away.
-Stellvia

James K
Flowing Fount of Yak Knowledge

3332 Posts

Posted - 08/14/2013 :  11:26:07  Show Profile  Reply with Quote
SELECT COALESCE(Col1,Col2) AS TheValue FROM YourTable
The rule with COALESCE is straightforward; travel from left to right and pick the first non-null value you see. So in this case, if Col1 is not null, that is what you will get. If Col1 is NULL, you will get whatever is in Col2.

Now if you want to assign that to a variable, you need to pick one row from the table. Otherwise, what will get assigned is not predictable.
SELECT TOP(1) @var = COALESCE(Col1,Col2) AS FROM YourTable ORDER BY Col1,Col2

Edited by - James K on 08/14/2013 11:27:44
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000