0to60 said:
I have a fairly complicated sproc that returns data. I'd like to use
this sproc in a buncha different places, but I'll need differing
conditions in my WHERE clause. Like, sometimes I'll be selecting all
the customers where State = 'IL', or maybe where CustomerName LIKE
"ABC%'.
What's the best way to do this? Right now I'm DECLAREing a table,
inserting the rows from the sproc, then selecting from the table and
applying my where clause to that.
That is difficult to answer without more knowledge about the problem
at hand.
If the "fairly complicated stored procedure" is a single (but complicated)
SELECT, or can be written as one, then the best solution is do as Celko
suggests and put in a view on an inline table function. This will give
you the best performance when you add certain subconditions.
However, it may not be possible to write the procedure that way, one
way or another. The disadvantage with running the basic SELECT, and
then do the final filtering is that if the basic SELECT to get all
possible rows takes five seconds, it still take five seconds to get
all customers whose names start with ABC, when a direct query would have
run in 100 ms, thanks to an index on customer name.
Therefore it may be better to add these possible conditions as parameters
to the procedure, but you need to use them with care to get good
performance. (And this is often contradictory with getting maintainable
code in these contexts.)
Of course, if this complicated stored procedure itself completes in 100 ms,
and is not executed 100 times a second, there is no performance issue
at all, and in that case your current approach is probably the best.
--
Erland Sommarskog, SQL Server MVP, (e-mail address removed)
Links for SQL Server Books Online:
SQL 2008:
http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005:
http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
SQL 2000:
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx