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:
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 :-(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
In reply to Re^3: Moving SQL from perl to Stored Procedures - MSSQL tricks, dynamic paging
by Jenda
in thread Moving SQL from perl to Stored Procedures
by imp
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |