Solved

SQL Server Select Statement Coalesce

Posted on 2014-10-01
5
194 Views
Last Modified: 2014-10-01
create table #temp
  (col int)
 
  insert into #temp
  select 1
  union select null
 
 
  declare @column as int
  set @column = null
   
  select *
  from #temp
  where col = coalesce(@column,col)

the sample table above has two records.  one null and one with a value.  If the parameter is null, I would like both records to be returned, however if the value = 1, then I would like to only return the value that equals 1.  I think I've done this with coalesce once before, however I can't recall the exact script.  

Thoughts?
0
Comment
Question by:yanci1179
  • 2
  • 2
5 Comments
 
LVL 39

Expert Comment

by:Kyle Abrahams
Comment Utility
select *
  from #temp
  where col = isnull(@column,0)
0
 
LVL 24

Expert Comment

by:Phillip Burton
Comment Utility
Does this work?

where not(col <> coalesce(@column,col))

Open in new window

0
 

Author Comment

by:yanci1179
Comment Utility
Hi Kyle, the statement doesn't return anything when @column is null.  


Hi Phillip,
the statement only returns 1 record when the @column is null.

Thank you both.  What I would like is if @column is null all records to show up.  if @column = 1, then only return the matching records.
0
 
LVL 24

Accepted Solution

by:
Phillip Burton earned 500 total points
Comment Utility
Belt and braces.

Where @column is null or col=@column

Open in new window

0
 

Author Closing Comment

by:yanci1179
Comment Utility
Awesome!! thank you!!
0

Featured Post

Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

Join & Write a Comment

When you hear the word proxy, you may become apprehensive. This article will help you to understand Proxy and when it is useful. Let's talk Proxy for SQL Server. (Not in terms of Internet access.) Typically, you'll run into this type of problem w…
Let's review the features of new SQL Server 2012 (Denali CTP3). It listed as below: PERCENT_RANK(): PERCENT_RANK() function will returns the percentage value of rank of the values among its group. PERCENT_RANK() function value always in be…
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Viewers will learn how the fundamental information of how to create a table.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now