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

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Using Coalesce to assign value to variable?

Author  Topic 

Eagle_f90
Constraint Violating Yak Guru

424 Posts

Posted - 2013-08-14 : 11:05:08
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
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-08-14 : 11:26:07
[code]SELECT COALESCE(Col1,Col2) AS TheValue FROM YourTable[/code]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.[code]SELECT TOP(1) @var = COALESCE(Col1,Col2) AS FROM YourTable ORDER BY Col1,Col2[/code]
Go to Top of Page
   

- Advertisement -