Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

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

Constraint Violating Yak Guru

424 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.

James K
Flowing Fount of Yak Knowledge

3873 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  
 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.02 seconds. Powered By: Snitz Forums 2000