Question

IIf...Else statement problem in SQL statement

Asked by: Jatherton

I am attempting to use the following SQL statement in my asp page to produce a ordered by search results recordset. I pass the recordset to a page to list results using a function. I am hanging on this SQL problem. It keeps telling me I am 'Syntax error (missing operator) in query expression '. Can someone give me some advice or a good place to look for an answer?

strSQL = "SELECT [tblMembers].[LastName], [tblMembers].[FirstName], [tblMembers].[DOB], " _
& "[tblHousehold].[Address], [tblHousehold].[HomePhone], [tblHousehold].[DaytimePhone], " _
& "(IIf([tblMembers].[LastName]=" & strLastName & ",1,0)+" _
& "IIf([tblMembers].[FirstName]=" & strFirstName & ",1,0)+" _
& "IIf([tblMembers].[DOB]=" & datDOB & ",1,0)+" _
& "IIf([tblHousehold].[Address]=" & strAddress & ",1,0) AS bytHits) " _
& "FROM tblHousehold INNER JOIN tblMembers ON " _
& "[tblHousehold].[HouseholdID]=[tblMembers].[HouseholdId] " _
& "WHERE " _
& "[tblMembers].[LastName]='" & strLastName & "' Or [tblMembers].[FirstName]='" & strFirstName & "' " _
& "Or [tblMembers].[DOB]='" & datDOB & "' Or [tblHousehold].[Address]='" & strAddress & "' "

strSQL = strSQL & " ORDER BY IIf(([tblMembers].[LastName]='" & strLastName & "'),1,0)+IIf(([tblMembers].[FirstName]='" & strFirstName & "'),1,0)+" _
& "IIf(([tblMembers].[DOB]='" & datDOB & "'),1,0)+IIf(([tblHousehold].[Address]='" & strAddress & "'),1,0) DESC;"

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-04-23 at 08:27:47ID20965167
Tags

else

,

iif

,

problem

,

statement

Topic

Active Server Pages (ASP)

Participating Experts
4
Points
50
Comments
28

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Iif Dilemma
    Hello all, I've checked for a possible solution to this dilemma and I've found that Iif statements in queries don't like the word "like", so I'm trying to see if there's another solution. I have a query in which I'm trying to pull either all records, all records li...
  2. IIf statement
    I am trying to run an iif statement like the following and for some reason the last part with the and does not work the formula passes as correct and will run but will not effect the outcome. This is an update statement in access IIf([table1!field1] Is Null,"test1&quo...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: alorentzPosted on 2004-04-23 at 08:32:13ID: 10900822

The use of all the IIF is highly unecessary.  You can do all you need to by just extending the WHERE clause.

 

by: alorentzPosted on 2004-04-23 at 08:33:37ID: 10900849

And if need be then use Response.write to review the formatting SQL:

strSQL = "SELECT [tblMembers].[LastName], [tblMembers].[FirstName], [tblMembers].[DOB], " _
& "[tblHousehold].[Address], [tblHousehold].[HomePhone], [tblHousehold].[DaytimePhone], " _
& "(IIf([tblMembers].[LastName]=" & strLastName & ",1,0)+" _
& "IIf([tblMembers].[FirstName]=" & strFirstName & ",1,0)+" _
& "IIf([tblMembers].[DOB]=" & datDOB & ",1,0)+" _
& "IIf([tblHousehold].[Address]=" & strAddress & ",1,0) AS bytHits) " _
& "FROM tblHousehold INNER JOIN tblMembers ON " _
& "[tblHousehold].[HouseholdID]=[tblMembers].[HouseholdId] " _
& "WHERE " _
& "[tblMembers].[LastName]='" & strLastName & "' Or [tblMembers].[FirstName]='" & strFirstName & "' " _
& "Or [tblMembers].[DOB]='" & datDOB & "' Or [tblHousehold].[Address]='" & strAddress & "' "

strSQL = strSQL & " ORDER BY IIf(([tblMembers].[LastName]='" & strLastName & "'),1,0)+IIf(([tblMembers].[FirstName]='" & strFirstName & "'),1,0)+" _
& "IIf(([tblMembers].[DOB]='" & datDOB & "'),1,0)+IIf(([tblHousehold].[Address]='" & strAddress & "'),1,0) DESC;"

Response.write "SQL: " & strSQL

Then see where the missing ' is...

 

by: JathertonPosted on 2004-04-23 at 08:42:29ID: 10900946

But I believe that would not work in my particular situation.  Please let me know if I am wrong.  

The reason I am using the IIf statment is to rate the matches returned by the SQL statment.
I have up to 4 criteria that are passed via my form (txtLastName, txtFirstName, txtDOB and txtAddress).  All four criteria may be passed with values or perhaps just one, two or three of them will be passed with values.  I want to find records that match any of the criteria (search) values passed to the SQL statement, but I want to order the results based on the closest match to the search criteria.

i.e. if we passed LastName=Smith DOB=03/11/90

Then

Results:

LastName           FirstName             DOB                Address
Smith                  David                 03/11/90         1234 Any Street
Smith                  Carol                 01/12/88         1234 Any Street
Smith                  Frank                06/19/04          3345 Filmore Street
Gaines                 Dean                 03/11/90          5609 Washington Avenue

Does that shed some light on it?

 

by: JathertonPosted on 2004-04-23 at 08:43:34ID: 10900954

oops, sorry you posted again before I submitted my response to your first response.  Sorry

 

by: Lord_McFlyPosted on 2004-04-23 at 08:47:40ID: 10901003

Firstly you should know that the syntax for using IIF is as follows...

IIF(condition,true,false)

and if nested...

IFF(condition,true,IIF(condition,true,false)

I'm just trying to organise you query using the correct syntax.

 

by: Lord_McFlyPosted on 2004-04-23 at 08:55:46ID: 10901088

At the moment I have you query as...

SELECT FirstName, LastName, DOB, Address, HomePhone, DayTimePhone
FROM tblHousehold INNER JOIN tblMembers ON tblMembers.HouseholdID = tblHousehold.HouseholdID
WHERE FirstName = 'Peter' OR
LastName = 'Roome' OR
DATEDIFF('d',DOB,'11/10/1972') = 0 OR
Address = 'MyAddress'

Can you describe in more detail what you expect the query to do and how you expect them to be sorted - cheers.

 

by: JathertonPosted on 2004-04-23 at 09:01:15ID: 10901148

I want to be able to rate (sorry for lack of a better word) the search criteria passed to the SQL statment.  The user may enter one, two, three or all four of the criteria to be passed.  I want to be able to show closest matches DESC (i.e. if all 4 search criteria fields are submitted and a record matches all 4 search criteria then list it first), but I do want to show all records that match any of the search criteria fields.  

So if all 4 match list it
and then if another record matches 3 then list it
and if another record matches 2 then list it
and if another record matches 1 then list it...

 

by: Lord_McFlyPosted on 2004-04-23 at 09:03:09ID: 10901167

If only some of you values are passed then build you query accordingly...

sQuery = "SELECT FirstName, LastName, DOB, Address, HomePhone, DayTimePhone " &_
               "FROM tblHousehold INNER JOIN tblMembers ON tblMembers.HouseholdID = tblHousehold.HouseholdID WHERE " &_

If txtFirstName <> "" then
     sQuery = sQuery & "FistName = '" & txtFirstName & "' OR "
End If

If txtLastName <> "" then
     sQuery = sQuery & "LastName = '" & txtLastName & "' OR "
End If

If txtDOB <> "" then
     sQuery = sQuery & "DATEDIFF('d',DOB,'" & txtDOB & "') = 0 OR "
End If

If txtAddress <> "" then
     sQuery = sQuery & "Adrress = '" & txtAddress & "' OR "
End If

sQuery = Left(sQuery,Len(sQuery) - 3) & "ORDER BY LastName ASC, FistName ASC, DOB ASC, Address ASC"

..execute the query

 

by: alorentzPosted on 2004-04-23 at 09:03:56ID: 10901178

Are you familiar with the CONTAINS clause?  That may works?

 

by: alorentzPosted on 2004-04-23 at 09:05:22ID: 10901185

 

by: JathertonPosted on 2004-04-23 at 09:05:34ID: 10901188

But wouldn't I get an error, if say only the Address was passed?  Attaching the OR to the statement would make it balk, right?

 

by: JathertonPosted on 2004-04-23 at 09:06:30ID: 10901198

alorentz

Not familiar with the contains clause, but I am willing to check it out.

 

by: alorentzPosted on 2004-04-23 at 09:07:46ID: 10901209

Lord_McFly's answer is probably you're best bet, used it the other day.  The left function gets rid of the OR

 

by: JathertonPosted on 2004-04-23 at 09:59:41ID: 10901717

I am now getting the dreaded Too few parameters. Expected 1 error.  I know it is passing it because I have debugged the sql statement.  What gives?

strSQL = "SELECT FirstName, LastName, DOB, Address, HomePhone, DayTimePhone " &_
                 "FROM tblHousehold INNER JOIN tblMembers ON tblMembers.HouseholdID = tblHousehold.HouseholdID WHERE "

            If strFirstName <> "" then
                       strSQL = strSQL & "FirstName = '" & strFirstName & "' OR "
            End If

            If strLastName <> "" then
                       strSQL = strSQL & "LastName = '" & strLastName & "' OR "
            End If

            If datDOB <> "" then
                       strSQL = strSQL & "DATEDIFF('d',DOB,'" & datDOB & "') = 0 OR "
            End If

            If strAddress <> "" then
                       strSQL = strSQL & "Address = '" & strAddress & "' OR "
            End If

      strSQL = Left(strSQL,Len(strSQL) - 3) & "ORDER BY LastName ASC, FistName ASC, DOB ASC, Address ASC"

 

by: alorentzPosted on 2004-04-23 at 10:15:39ID: 10901915

Do reponse.write strSQL to see what it writes so you can debug...

 

by: faironPosted on 2004-04-23 at 11:01:30ID: 10902327

Use ASP to structure your SQL.

So have the basic structure at the end:

strSQL = "SELECT " & selectVar & " WHERE " & whereVar1 & whereVar2 & " ORDER BY " & orderbyVar1 & orderbyVar2 & ascOrDesc



So then before the query you can have code to determine what goes in the variables/SQL.

i.e.
whereVar1 = "[tblMembers].[LastName]='" & strLastName & "'"
whereVar2 = ""

If strFirstName <> "" then
      whereVar2 = " AND firstName = " & strFirstName
End If

 

by: alorentzPosted on 2004-04-23 at 11:06:50ID: 10902370

@fairon - let's not make this more confusing than necessary... The idea would be to get it to work first as basic as possible.

 

by: hoenthPosted on 2004-04-23 at 11:25:13ID: 10902544

I see you have made good head way, but i have a couple of comments.

First, if the code you posted is actually what you are using, you have a typo in your Order By statement (FistName  should be FirstName)

Second, you can do away with the need to strip the final or by change the where clause to:

 "FROM tblHousehold INNER JOIN tblMembers ON tblMembers.HouseholdID = tblHousehold.HouseholdID WHERE 1 <> 1 "

And each of the tests for search values would be changed to:

         If strFirstName <> "" then
                    strSQL = strSQL & " OR FirstName = '" & strFirstName & "'"
          End If

This also solves the problem if no search criteria are passed. Otherwise your where clause would be empty

Fairon suggestion is a very good one. A similar method would be replicate the build of the order by clause at the same time you build the where clause. in other words, the following:

         If strFirstName <> "" then
                    strSQL = strSQL & " OR FirstName = '" & strFirstName & "'"
                   strOrderby = strOrderby & ",FirstName "
          End If

So putting it all together, you get something like this:

strOrderBy = " Orderby 1"
strSQL = "SELECT FirstName, LastName, DOB, Address, HomePhone, DayTimePhone " &_
                 "FROM tblHousehold INNER JOIN tblMembers ON tblMembers.HouseholdID = tblHousehold.HouseholdID WHERE 1<>1 "

          If strFirstName <> "" then
                    strSQL = strSQL & " OR FirstName = '" & strFirstName & "'"
                    strOrderby = strOrderby & ", FirstName "
          End If

          If strLastName <> "" then
                    strSQL = strSQL & " OR LastName = '" & strLastName & "'"
                    strOrderby = strOrderby & ", LastName "
          End If

          If datDOB <> "" then
                    strSQL = strSQL & " OR DATEDIFF('d',DOB,'" & datDOB & "') = 0"
                    strOrderby = strOrderby & ", DOB"
          End If

          If strAddress <> "" then
                    strSQL = strSQL & " OR Address = '" & strAddress & "'"
                    strOrderby = strOrderby & ", Address "
          End If

     strSQL = strSQL & strOrderby

I also agree with alorentz. Do a response.write on strSQL after the last statment, but before you attempt to run it.

Then you can copy the entire string and paste it into whatever query engine is avalable for the database you are using.

Good luck

 

by: faironPosted on 2004-04-23 at 11:25:50ID: 10902548

yeah maby you're right...

But I'd always find it easier to program using the scripting language rather than with SQL...

 

by: hoenthPosted on 2004-04-23 at 11:34:17ID: 10902626

I guess that I should also point out that if the search criteria is empty, you would get no records. If instead you want to return all records and you want to specify a sort order if no records are returned, then you need to set up two defaults, one for the where clause, and one for the orderby clause.

something to the affect
If strLastName <> "" and strFirstName <> "" and datDOB <> "" and strAddress <> "" Then
   strSQL = StrSQL & " OR 1 = 1"
   strOrderBy = StrOrderby & "LastName, FirstName, DOB, Address"
End If

You should place this If statement directly after the other ones.

Also, if you want to have LastName before Firstname in your Order by statement when they both are supplied in the search criteria, switch the two related If statements above.

 

by: JathertonPosted on 2004-04-23 at 12:54:02ID: 10903315

The only problem now (and correct me if I am wrong) but when I get to the sort order part  I am sorting the DOB on the actual DOB and not whether it came back as a hit on the search criteria.  

I know that is confusing, but say when i search on the following:

I enter:
LastName: Smith
DOB: 03/11/72

I get the right records, but the wrong sort order:

LastName        FirstName        DOB              Address
Smith                 David          01/26/93       1234 Any City
Smith                 Sarah         03/11/72        2345 Rhodes St.

When what I want is the closest match on top:

LastName        FirstName        DOB              Address
Smith                 Sarah         03/11/72        2345 Rhodes St.
Smith                 David          01/26/93       1234 Any City



 

by: hoenthPosted on 2004-04-23 at 13:06:29ID: 10903410

I understand now. Thus the need for scoring.

Are you using MS Access as the datbase?

 

by: JathertonPosted on 2004-04-23 at 13:09:43ID: 10903444

yes

 

by: hoenthPosted on 2004-04-23 at 13:29:46ID: 10903613

Ok, here is the trick,

We will need to revise the sql code slightly. Basically, we are creating a numeric score based on a bunch of boolean comparisons. The boolean values are converted to integers and added together. Whenever there is a match for one of the critieria, a -1 is added to the Orderby value. Access uses -1 to indicate true. So the best score is a -4, if you used all 4 criteria.

The Orderby statement would look something like this: Order by 0 + Cint([FirstName]='Smith') + Cint([Address]='123 MyStreet')

strOrderBy = " Orderby 0"
strSQL1 = "SELECT FirstName, LastName, DOB, Address, HomePhone, DayTimePhone " & _
  " FROM tblHousehold INNER JOIN tblMembers ON tblMembers.HouseholdID = tblHousehold.HouseholdID WHERE 1<>1 "


          If strLastName <> "" then
                    strSQL = strSQL & " OR LastName = '" & strLastName & "'"
                    strOrderby = strOrderby & " + Cint([LastName= '" & strLastName & "') "
          End If


          If strFirstName <> "" then
                    strSQL = strSQL & " OR FirstName = '" & strFirstName & "'"
                    strOrderby = strOrderby & " + Cint([FirstName]='" & strFirstName & "') "
          End If

          If datDOB <> "" then
                    strSQL = strSQL & " OR DATEDIFF('d',DOB,'" & datDOB & "') = 0"
                    strOrderby = strOrderby & " + Cint([DOB]='" & datDOB & "') "

          End If

          If strAddress <> "" then
                    strSQL = strSQL & " OR Address = '" & strAddress & "'"
                    strOrderby = strOrderby & " + Cint([Address ]='" & strAddress & "') "
          End If

     strSQL = strSQL & strOrderby

 

by: JathertonPosted on 2004-04-23 at 18:45:12ID: 10905481

It is still hanging, on the DOb part of the OrderBy statment.

 

by: hoenthPosted on 2004-04-24 at 04:31:29ID: 10906996

OK, try this.

  If datDOB <> "" then
                    strSQL = strSQL & " OR DATEDIFF('d',DOB,'" & datDOB & "') = 0"
                    strOrderby = strOrderby & " + Cint([DOB]=#" & datDOB & "#) "

   End If

 

by: JathertonPosted on 2004-04-24 at 10:00:54ID: 10908251

Worked like a charm.  Thanks to all of you for the help and guidance.

 

by: hoenthPosted on 2004-04-24 at 13:04:03ID: 10909069

Your very welcome
One last comment. The above will sort by the score. But if you have a tie, then there is no further defined sort order.

To defeat this, you could merge the earlier sort order definition with the scoring definition, appending the fields by which you want to sort if there is a tie after the score. You would need to build a second Orderby string using the field names, as we previously had.

Then append that after the score orderby string.

the the order by computed string would look like: order by 0 + Cint([FirstName]='Smith') + Cint([Address]='123 MyStreet'), FirstName, Address

Good luck, and thanks for the points.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...