TSQL’s Equivalent to Create New Query Based on Previous Query Result

I have a table called PRICE with two columns, unitPrice and resellerId. From my application, I use the following code (pseudo) to query the unitPrice for a given reseller. Basically I use the unitPrice if the resellerId presents in the table. Otherwise I use the default unitPrice (for a special reseller with Id 0)

resultSet = select unitPrice from PRICE where resellerId=123
if(resultSet.isEmpty()){
   resultSet = select unitPrice from PRICE where resellerId=0
}

This works all fine. However, I want to combine the two queries above into one SQL statement that returns the unitPrice without the application code checking the condition (i.e. without checking resultSet.isEmpty()).

Based on Gordon Linoff, the following solution should work:

select top 1 unitPrice
from PRICE
where resellerId in (123, 0)
order by (case when resellerId = 0 then 1 else 0 end);
Advertisements
This entry was posted in Database and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s