in reply to Re: Moving SQL from perl to Stored Procedures - MSSQL tricks, dynamic paging
in thread Moving SQL from perl to Stored Procedures

Use cursors! Update: BTW: These dynamic where clauses are very expensive because the optimizer cannot optimize them. Better way: Generate SQL-Statements with a fixed filter, and execute them from within a procedure. This is much more performant. There was an article in SQL - mag in the black belt sql column recently. Maybe I should meditate someday about "SQL-cursors for the unwary" or something like that.
  • Comment on Re^2: Moving SQL from perl to Stored Procedures - MSSQL tricks, dynamic paging

Replies are listed 'Best First'.
Re^3: Moving SQL from perl to Stored Procedures - MSSQL tricks, dynamic paging
by Jenda (Abbot) on Sep 09, 2006 at 10:32 UTC

    You mean build an SQL statement in a nvarachar variable and then execute it? Well well well ... this has two big problems. The first being that this way you force the server to generate a query plan for each execution which may be a rather expensive operation. And the second, even more important, is that this is prone to SQL injection attacks. And it's even more dangerous than SQL statements built in the pages/scripts. First because it's kinda hidden in something that's by most believed to be safe and second because the statement is executed with the permissions of the stored procedure owner (usually dbo!) instead of the permissions of the user accessing the database!

    I can't say I never use this, but I do try to take this as a last resort solution. It's much better, even if not very convenient to branch out and write several SELECT statements. That way the server may generate and REMEMBER the query plans for each of the cases and there is nothing ad-hoc generated and therefore dangerous:

    CREATE PROCEDURE [dbo].[dynamic_example] @lastname varchar(50) = NULL, @firstname varchar(50) = NULL AS BEGIN IF (@lastname IS NULL) IF (@firstname IS NULL) SELECT * from Users ELSE SELECT * from Users WHERE (users.firstname LIKE @firstname) ELSE IF (@firstname IS NULL) SELECT * from Users WHERE (users.lastname LIKE @lastname) ELSE SELECT * from Users WHERE (users.lastname LIKE @lastname) AND (users.firstname LIKE @firstname) END GO
    I know it's inconvenient, especially as the number of conditions increases, but it's the safest and most efficient solution. It's a shame I can't use some macros in SQL :-(