SQL statements containing a lot of ORs in the WHERE statement - Best Practice

SQL statements containing a lot of ORs in the WHERE statement - Best Practice

Post by rayd » Wed, 19 May 2004 22:54:20


SELECT * FROM table WHERE IN (1, 10, 17 ....)

If you wish to pass in a comma delimited list from ASP,
see this site for possible solutions:
http://www.yqcomputer.com/ ~sommar/arrays-in-sql.html



page.
 
 
 

SQL statements containing a lot of ORs in the WHERE statement - Best Practice

Post by Andre Beie » Wed, 19 May 2004 22:56:39

Hi,

I have a SQL statement with a lot of ORs in it

SELECT * FROM table WHERE id = 1 OR id = 10 OR id = 17 ....

The number of ORs vary from 1 TO 15.
I could just create 15 ORs, but I don't think this is a good and efficient
thing to do.

I want to create a STORED PROCEDURE that will be executed from an ASP page.

What is the best way to do something like this?

Thanks in advance.

Andre

 
 
 

SQL statements containing a lot of ORs in the WHERE statement - Best Practice

Post by Adam Macha » Wed, 19 May 2004 23:05:28

http://www.yqcomputer.com/ ~sommar/dyn-search.html



page.
 
 
 

SQL statements containing a lot of ORs in the WHERE statement - Best Practice

Post by Aaron Bert » Wed, 19 May 2004 23:09:05

The other option is to use a comma-separated list, and use dynamic SQL to
say EXEC(' ... WHERE ID IN ('+@list')').

To make it relational (and better for performance, I would bet, depending on
several factors), you could stuff the comma-separated list into a table, and
then join on that. See http://www.yqcomputer.com/
a comma-separated list as an "array" of sorts, that you can stuff into a
single-column table.

--
Aaron Bertrand
SQL Server MVP
http://www.yqcomputer.com/






page.