Wednesday, March 7, 2012

how to add a where clause by parameter in a stored procedure

What i want is to add by parameter a Where clause and i can not find how to do it!
CREATE PROCEDURE [ProcNavigate]
(
@.id as int,
@.whereClause as char(100)
)
AS
Select field1, field2 Where fieldId = @.id /*and @.WhereClause */
GO

thx
What error did you get? That sproc defintion looks fine to me apart from the fact that you've missed the FROM clause from the parameterised SQL statement.

-Jamie|||thx for the reply.

You are right. I forgot the from clause.

CREATE PROCEDURE [ProcNavigate]
(
@.id as int,
@.whereClause as char(100)
)
AS
Select field1, field2 FROM Table1 Where fieldId = @.id /*and @.WhereClause */
GO
I get only a syntax error when checking the procedure syntax|||

SQL Server does not support "parameterizing" the WHERE clause or any syntactic construct.

You have to construct the SQL String using string concatenation operations and then execute the constructed string using the dynamic EXEC statement.

CREATE PROCEDURE [ProcNavigate]
(
@.id as int,
@.whereClause as char(100)
)
AS
BEGIN
DECLARE @.mdstring nvarchar(300);
set @.cmdstring = "SELECT field1, field2 FROM T WHERE fieldID = " + @.id +
" AND " + @.whereClause;
EXEC(@.cmdstring);
END
GO

|||Personally, I dislike the above mentioned method. Besides the fact that it opens you to all sorts of bad stuff.

What you can do is make the parameters nullable, and do a case statement on the where part of the clause:

create procedure pSomethingOrAnother
(
@.p_lID integer,
@.p_lWhereItem1 integer,
@.p_sWhereItem2 varchar(50)
)
as

set nocount on

select
t.Field1,
t.Field2
from
TableName t
where
t.FieldID = @.p_lID
and (case when ISNULL(@.p_lWhereItem1, 0) = 0 then 0 else t.FieldToCheck1 end) = ISNULL(@.p_lWhereItem1, 0)
and (case when ISNULL(@.p_lWhereItem2, '') = '' then '' else t.FieldToCheck2 end) = ISNULL(@.p_sWhereItem2, '')

set nocount off

No magic values, no string concatenation, no million if statements. The only time this won't work so well is when you are looking for the value NULL in a field, but you can separate those instances out with an IF statement for that field.

No comments:

Post a Comment