Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

EXECuting a string to run a SELECT?

Status
Not open for further replies.

markSaunders

Programmer
Jun 23, 2000
196
GB
Is is possible to have a stored proc that will run against a table that is specified as a parameter - such as....

Code:
CREATE PROCEDURE usp_items	@iItem INT=0,
				@vItem varchar(50)
AS

DECLARE @string varchar(255)
SET @string = 'SELECT * FROM ' + @vItem + ' WHERE (' + @vItem + 'ID=' + cast(@iItem as varchar) + ') or (@i' + @vItem + '=0)   ORDER BY title'

execute @string
GO

where Item represents the table

This would allow me to use one stored procedure against 5 almost identical tables rather than 5 stored procs.

The error message I receive is
Code:
Server: Msg 2812, Level 16, State 62, Line 17
Could not find stored procedure 'SELECT * FROM skill WHERE (skillID=0) or (@iskill=0)   ORDER BY title'.

as it's obviously trying to execute a stored proc and not the actual command line I have defined.

Any ideas?

mark Mark Saunders :)
 
Hi Mark

Try this out..... i have put a bracket around @String after execute....
CREATE PROCEDURE usp_items @iItem INT=0,
@vItem varchar(50)
AS

DECLARE @string varchar(255)
SET @string = 'SELECT * FROM ' + @vItem + ' WHERE (' + @vItem + 'ID=' + cast(@iItem as varchar) + ') or (@i' + @vItem + '=0) ORDER BY title'

execute(@string)
GO

regards

sunil
 
I think an issue is going to be that when the Select runs, it will not have any idea what the variable @iskill is.

WHERE (skillID=0) or (@iskill=0)
 
Assuming your @string is a good SQL statement, all you should need to do is: Execute (@string) rather than Execute @string.
 
The brackets worked - cheers.

Also, i had put the iskill=0 incorrectly as it should have read 0=0

Cheers for the help!

M Mark Saunders :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top