all groups > sql server programming > december 2004 >
You're in the

sql server programming

group:

Help on Dynamic SELECT



Re: Help on Dynamic SELECT Nigel Rivett
12/4/2004 2:49:45 PM
sql server programming: Not a good idea but

exec ('SELECT * FROM Table WHERE ' + @QueryClause)

beware of injection.
This is also binding the app to the database structure which is never a
good idea. Better to pass the individual search parameters and let the
SP build the search.

Nigel Rivett
www.nigelrivett.net

*** Sent via Developersdex http://www.developersdex.com ***
Re: Help on Dynamic SELECT Colin Angus Mackay
12/4/2004 10:46:35 PM
There are two ways to do this that I can think of.

One of them is susceptible to SQL Injection attacks so I won't discuss it.

The other is to create a stored procedure like this:

CREATE PROCEDURE dbo.MyProc
@country AS int,
@name AS varchar(32),
@city AS varchar(32)
AS
SELECT *
FROM MyTable
WHERE (@country IS NULL OR country=@country)
AND (@name IS NULL OR name=@name)
AND (@city IS NULL OR city=@city)
GO

Does this help?

Regards,
Colin.

[quoted text, click to view]

--
- Developer Services Provider: http://wdevs.com
For Blogs, FTP, Mail, Forums, Members Product Areas
Help on Dynamic SELECT Andrea
12/4/2004 11:18:55 PM
I need to create a stored proc that run a select with dynamic where clause.
For example:

SELECT * FROM Table WHERE country=1
SELECT * FROM Table WHERE name='james'
SELECT * FROM Table WHERE country=1 AND name='james'
SELECT * FROM Table WHERE city='NewYork'
SELECT * FROM Table WHERE name='james' AND city='NewYork'
SELECT * FROM Table WHERE name='james' AND city='NewYork' AND country=1
SELECT * FROM Table WHERE city='NewYork' AND country=1

I'd like to pass the where clause to the stored procedure from my code.
If I execute the query from the code I can create a string with the select
than execute the string, but I can't find any solution to use a stored proc.

I tried to create a parameter

@QueryClause as varchar

and use it like this

SELECT * FROM Table WHERE @QueryClause

but doesn't works, because the parameter is seen like a value.

How can I solve this problem.

Thanks for your help.

Andrea

AddThis Social Bookmark Button