Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute sql text passed as an sp parameter?

I have a stored procedure with an nvarchar parameter. I expect callers to supply the text for a sql command when using this SP.

How do I execute the supplied sql command from within the SP?

Is this even possible?-

I thought it was possible using EXEC but the following:

EXEC @script

errors indicating it can't find a stored procedure by the given name. Since it's a script this is obviously accurate, but leads me to think it's not working as expected.

like image 861
Dane O'Connor Avatar asked Sep 08 '26 14:09

Dane O'Connor


1 Answers

Use:

BEGIN

  EXEC sp_executesql @nvarchar_parameter

END

...assuming the parameter is an entire SQL query. If not:

DECLARE @SQL NVARCHAR(4000)
SET @SQL = 'SELECT ...' + @nvarchar_parameter

BEGIN

  EXEC sp_executesql @SQL

END

Be aware of SQL Injection attacks, and I highly recommend reading The curse and blessing of Dynamic SQL.

like image 157
OMG Ponies Avatar answered Sep 11 '26 06:09

OMG Ponies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!