Home All Groups Group Topic Archive Search About

Help - using sp_executesql with dynamic query...dynamic parameters??

Author
22 Oct 2005 1:42 PM
Lisa Forde
Hi. I'm attempting to write a Stored Procedure that creates an SELECT
statement. Belwo is an example of what I am tryign except that my actually
query have many more parameters most of which can be eliminated.

@sQUERy NVarchar(2000),
@sParams NVarchar(2000)

@sQuery = 'SELECT * FROM Clients WHERE '

IF ISNULL(@sFirstName,'') <> ''  BEGIN
    @sQuery = @sQuery+' FirstName LIKE @sFirstName '
    @sParams = ' @sFirstName VARCHAR(30),'
END

IF ISNULL(@sLastName,'') <> ''  BEGIN
    IF LEN(@sParams) > 0
        @sQuery = @sQuery+' AND LastName LIKE @sLastName '
    ELSE
        @sQuery = @sQuery+' LastName LIKE @sLastName '

    @sParams = ' @sLastName VARCHAR(30)'
END

  IF LEN(@sParams) > 0
        @sQuery = @sQuery+' AND Cancelled=0'
    ELSE
        @sQuery = @sQuery+' Cancelled=0 '

    @sParams = ' @Cancelled    SMALLINT'

EXEC sp_executesql @sQuery,@sParams, <WHAT DO I PUT HERE??>

Can it even work?

Thanks for any suggestions!

Author
22 Oct 2005 2:33 PM
Erland Sommarskog
[posted and mailed, please reply in news]

Lisa Forde (1fo***@caribsurf.com) writes:
> Hi. I'm attempting to write a Stored Procedure that creates an SELECT
> statement. Belwo is an example of what I am tryign except that my actually
> query have many more parameters most of which can be eliminated.
>...
> EXEC sp_executesql @sQuery,@sParams, <WHAT DO I PUT HERE??>
>
> Can it even work?

You put the parameters. I have an example of a dynamic search routine
at http://www.sommarskog.se/dyn-search.html#sp_executesql which hopefully
can be of help for you.


--
Erland Sommarskog, SQL Server MVP, esq***@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinfo/productdoc/2000/books.asp
Author
22 Oct 2005 2:42 PM
Lisa Forde
Perfect!

Thanks.

Show quote
"Erland Sommarskog" <esq***@sommarskog.se> wrote in message
news:Xns96F7A82091A39Yazorman@127.0.0.1...
> [posted and mailed, please reply in news]
>
> Lisa Forde (1fo***@caribsurf.com) writes:
> > Hi. I'm attempting to write a Stored Procedure that creates an SELECT
> > statement. Belwo is an example of what I am tryign except that my
actually
> > query have many more parameters most of which can be eliminated.
> >...
> > EXEC sp_executesql @sQuery,@sParams, <WHAT DO I PUT HERE??>
> >
> > Can it even work?
>
> You put the parameters. I have an example of a dynamic search routine
> at http://www.sommarskog.se/dyn-search.html#sp_executesql which hopefully
> can be of help for you.
>
>
> --
> Erland Sommarskog, SQL Server MVP, esq***@sommarskog.se
>
> Books Online for SQL Server SP3 at
> http://www.microsoft.com/sql/techinfo/productdoc/2000/books.asp
>

AddThis Social Bookmark Button