Discussion Locked

Execute an SQL string in SQL Stored Proc

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
How to execute a concatenated SQL string within a SQL Server Stored Procedure.

3 replies

by andrew

No problem.
Use Exec (execute) to run the built up SQL string:

Create Proc pListNames (@FieldName varchar(128),@FieldValue varchar(128))as
exec ('select * from authors where ' + @FieldName + ' = ' + "'" + @FieldValue + "'")

exec pListNames 'au_lname','white'

(If you're passing in string values, remember to wrap them in single quotes once they're in the proc)

The downside to this is that SQL Server can't compile the proc, so performance is poorer.

This discussion is closed to new replies.