Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 217
  • Last Modified:

How to force a return record even if none are found matching my criteria?

I'm trying to force a select query to return a record with default values IF the criteria does NOT find a matching value.

Example:

SELECT     Field1 + Field2 + Field3 + Field4 AS TotalFields, UniqueID
FROM       MyTable
WHERE     (UniqueID = 'DM') AND (SomeDateField = '3/31/2004')

If the select does not return any records, I need it to be forced to return at least one record with default values (that I can specify).

Is this possible?

Rob.
0
RobAinscough
Asked:
RobAinscough
  • 3
  • 2
  • 2
1 Solution
 
mokuleCommented:
SELECT     Field1 + Field2 + Field3 + Field4 AS TotalFields, UniqueID
FROM       MyTable
WHERE     (UniqueID = 'DM') AND (SomeDateField = '3/31/2004')
IF @@ROWCOUNT=0
          SELECT 0 AS TotalFields,'' AS UniqueID
0
 
mokuleCommented:
or
IF EXISTS( SELECT     Field1 + Field2 + Field3 + Field4 AS TotalFields, UniqueID
FROM       MyTable
WHERE     (UniqueID = 'DM') AND (SomeDateField = '3/31/2004')
)
    SELECT     Field1 + Field2 + Field3 + Field4 AS TotalFields, UniqueID
    FROM       MyTable
    WHERE     (UniqueID = 'DM') AND (SomeDateField = '3/31/2004')
ELSE
          SELECT 0 AS TotalFields,'' AS UniqueID
0
 
RobAinscoughAuthor Commented:
The IF EXISTS does work, thank you.  However, I'm trying to CREATE VIEW using the above construct and apparently VIEWs do NOT support the use of IF EXISTS...

hmmmm...
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Anthony PerkinsCommented:
>>However, I'm trying to CREATE VIEW using the above construct <<
It is always good to know ahead of time.  

Consider adding it to the original table and only displaying if the condition does not return any rows.
0
 
Anthony PerkinsCommented:
Friendly reminder:  This question has been classified as abandoned:
http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/Q_21305266.html
0
 
RobAinscoughAuthor Commented:
mokule answered my question with the information I originally provided so I've awarded the points, not his/her fault that my additional requirements couldn't work with that solution.
0
 
Anthony PerkinsCommented:
Fair enough.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now