Multiple Search Words for SQL

K

Keith

I have a small form which searches a SQL DB on several fields - ie.

WHERE Field1 = xxx AND Field2 = xxx AND Field3 = xxx

How can I do this so that if one search criteria is left blank, it ignores
it instead of trying to match it in the DB?
 
A

Aaron [SQL Server MVP]

You could say:

WHERE (@param1 IS NULL OR column1 = @param1)
or
WHERE column1 = COALESCE(@param1, column1)

Neither of these will use indexes, so performance might not be optimal.

If you have a small number of options, you could use IF statements to choose
a static SELECT statement, e.g.

IF @param1 IS NOT NULL AND @param2 IS NOT NULL
SELECT * FROM tbl WHERE column1 = @param1 AND column2 = @param2

IF @param1 IS NULL AND @param2 IS NOT NULL
SELECT * FROM tbl WHERE column2 = @param2

etc etc

If the number of options is large, you could try dynamic SQL (either a
stored procedure that builds the statement and executes it, or having ASP
build the query and send it as adCmdText).
 
B

Bullschmidt

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,801
Messages
2,569,658
Members
45,421
Latest member
DoreenCorn

Latest Threads

Top