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

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.

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.

you can just exec #sqlStatement from within your sp. Though, its not the best thing to do because it opens you up to sql injection. You can see an example here

You use EXECUTE passing it the command as a string. Note this could open your system up to serious vulnerabilities given that it is difficult to verify the non-maliciousness of the SQL statements you are blindly executing.

How do I execute the supplied sql command from within the SP?
Very carefully. That code could do anything, including add or delete records, or even whole tables or databases.
To be safe about this, you need to create a separate user account that only has dbreader permissions on just a small set of allowed tables/views and use the EXECUTE AS command to limit the context to that user.

Related

Dynamic SQL vs Parameterised query

Is this stored procedure considered Dynamic SQL or a Parameterised query?
CREATE PROCEDURE [dbo].[my_dodgy_sp]
#varchar1 varchar(50),
#varchar2 varchar(50)
AS
BEGIN
...
EXEC [dbo].[my_really_special_sp] #varchar1 #varchar2;
END
Extra chocolate donuts with cherries on top if you can tell me whether this is Dynamic / Parameterised:
CREATE PROCEDURE [dbo].[my_super_dodgy_sp]
#varchar1 varchar(50),
#varchar2 varchar(50),
#stored_procedure_name sysname
AS
BEGIN
...
EXEC #stored_procedure_name #varchar1 #varchar2;
END
EXEC [dbo].[my_really_special_sp] #varchar1 #varchar2;
Is not a Parameterised query, it is a normal call of a stored procedure.
It's depend on the content of [my_really_special_sp] if this will result in a Parameterised query.
Please provide more information, i would like to help you much more.
"Dynamic SQL" refers to building up a SQL Query String programatically. Such as adding joins, building up a where clause, etc.
Parameterised Queries are SQL Query Strings that contain variables, the values of which are supplied separately from the SQL Query String.
Neither of your examples fit these descriptions because they are both simple T-SQL calls within stored procedures.
It may seem pedantic, but if your application calls 'EXEC [dbo].[my_really_special_sp] #varchar1 #varchar2', then that is a parameterised query.
And if your SP calls sp_executesql 'EXEC [dbo].[my_really_special_sp] #var1 #var2', #var1 = 1, #var2 = 10 then...
sp_executesql is T-SQL call
'EXEC [dbo].[my_really_special_sp] #var1 #var2' is your parameterised query
#var1 = 1, #var2 = 10 are your parameters
The important point is that your examples are pre-compiled statements in an SP. The examples I tried to explain are strings that are passed to the SQL Server to parse, compile and execute.
If that string is made up programatically piece by piece, it's dynamic sql.
If that string contains variable references that are supplied separately, it is parameterised.
I hope that helps, though I can see that it may seem subjective.
As for your programming style. Your second SP has a minor 'vulnerability', in that if a user has access to it, they have access to all other SPs with the same signature, even if that user doesn't natively normally have access. This may be intentional, and/or you may validate the #spname parameter to close the vulnerability. Other than that, there is nothing I can see that can be faulted.

SQL Table "Pointer"?

Using SQl Server 2000 I have a stored procedure that joins 2 tables and then returns the data. I want this sp to be able to do this for whatever table name I pass into it, otherwise I'll have the exact same code with the exception of the table name 20 or so times in a giant if statement. Basically, how do I use a variable to point to a table, or is that allowed? Thanks.
You need dynamic SQL, start here The Curse and Blessings of Dynamic SQL to learn how to do it correctly so that nobody drops your tables or does anything else possible with SQL Injection
Try building the SELECT as a string and then calling EXEC and passing the string.
e.g.
declare #sql varchar(500)
set #sql = 'select whatever from ' + #tableName
exec #sql
One proc to do anything is usually a bad bad idea. 20 possible tables I might need to go to depending on the circumstances almost always indicates a database design that is bad. Read the article Denis posted on the curses and blessings of dynamic SQL.

Copy trigger from one database to another

Is it possible, in a script executed in MS SQL Server 2005, to copy a trigger from one database to another?
I've been asked to write a test script for a trigger my project is using. Our test structure is to create an empty database containing only the object under test, then execute a script on that database that creates all the other objects needed for the test, fills them, runs whatever tests are needed, compares the results against expected results, and then drops everything except the object under test.
I can't just create a database that is empty except for the trigger, because the trigger depends on several tables. My test script currently runs the CREATE TRIGGER after all the required tables are created, but this won't do because the test script isn't allowed to contain the object under test.
What's been suggested is that, instead of running a CREATE TRIGGER, I somehow copy the trigger at that point in the script from the live database to the test database. I've had a quick Google and haven't found a way to do this. Thus my question - is this even possible, and if so, how can I do it?
You could read the text of the trigger with sp_helptext (triggername)
Or you can select the text into a variable and execute that:
declare #sql varchar(8000)
select #sql = object_definition(object_id)
from sys.triggers
where name = 'testtrigger'
EXEC #sql
I have a stored procedure that copies a bunch of tables to a test database. To make it less prone to mistakes that could potentially change the wrong database, I want to avoid using USE and instead explicitly specify per statement which database the trigger is copied from and to.
With the help of this answer, I came up with this solution:
DECLARE #sql NVARCHAR(MAX);
EXEC SourceDB.sys.sp_executesql
N'SELECT #output = (SELECT OBJECT_DEFINITION(OBJECT_ID(''TriggerName'')))',
N'#output VARCHAR(MAX) OUTPUT',
#output = #sql OUTPUT;
EXEC DestDB.sys.sp_executesql #sql;

Dynamic View name in Table valued function

I'm passing View name as parameter in a Table Valued Function, and I want to fetch some data from that view by building a dynamic SQL and executing it by sp_executesql().
when try to execute the function, I get the error:
Only functions and extended stored procedures can be executed from within a function.
DBMS: SQL Server 2005
any workarounds?
set #SQLString =
N'select #Desc = Description from '
+ #TableName
+ ' where Code = #Code;'
execute sp_executesql #SQLString,
N'#Code nvarchar(500),
#Desc nvarchar(500) OUTPUT',
#Code = #Code,
#Desc=#Desc OUTPUT;
Well, you could wrap the dynamic SQL in an extended stored procedure. That would work, but I'd (strongly) advise against doing it.
SQL Server requires user-defined functions to be deterministic (with the exception of the aforementioned extended stored procedures) -- i.e. the results of the function should be uniformly predictable from the input parameters. Since stored procedures can access data from anywhere, use random numbers, etc., SQL Server will not allow you to use them inside a function.
There are other approaches you can use, such as prepopulating a table variable with your data, modifying your schema, and so forth, that will depend on your performance requirements and how you have the schema set up.
no unless you want to do a loopback query by calling an extended proc like xp_cmdshell
something like this, modify to fit your needs
CREATE FUNCTION fnBla(#id int)
RETURNS int
AS
BEGIN
DECLARE #SQL varchar(500)
SELECT #SQL='osql -S' +##servername +' -E -q "exec tempdb..prLog ''fnBla''"'
EXEC master..xp_cmdshell #SQL
RETURN #id
END
Just so that you know I would not do this this way since you are creating a loopback query and not executing the safest code
any reason you can't use a proc instead of a function?

How do I run SQL queries on different databases dynamically?

I have a sql server stored procedure that I use to backup data from our database before doing an upgrade, and I'd really like it to be able to run the stored procedure on multiple databases by passing in the database name as a parameter. Is there an easy way to do this? The best I can figure is to dynamically build the sql in the stored procedure, but that feels like its the wrong way to do it.
build a procedure to back up the current database, whatever it is. Install this procedure on all databases that you want to backup.
Write another procedure that will launch the backups. This will depend on things that you have not mentioned, like if you have a table containing the names of each database to backup or something like that. Basically all you need to do is loop over the database names and build a string like:
SET #ProcessQueryString=
'EXEC '+DatabaseServer+'.'+DatabaseName+'.dbo.'+'BackupProcedureName param1, param2'
and then just:
EXEC (#ProcessQueryString)
to run it remotely.
There isn't any other way to do this. Dynamic SQL is the only way; if you've got strict controls over DB names and who's running it, then you're okay just truncating everything together, but if there's any doubt use QUOTENAME to escape the parameter safely:
CREATE PROCEDURE doStuff
#dbName NVARCHAR(50)
AS
DECLARE #sql NVARCHAR(1000)
SET #sql = 'SELECT stuff FROM ' + QUOTENAME(#dbName) + '..TableName WHERE stuff = otherstuff'
EXEC sp_ExecuteSQL (#sql)
Obviously, if there's anything more being passed through then you'll want to double-check any other input, and potentially use parameterised dynamic SQL, for example:
CREATE PROCEDURE doStuff
#dbName NVARCHAR(50)
#someValue NVARCHAR(10)
AS
DECLARE #sql NVARCHAR(1000)
SET #sql = 'SELECT stuff FROM ' + QUOTENAME(#dbName) + '..TableName WHERE stuff = #pOtherStuff'
EXEC sp_ExecuteSQL (#sql, '#pOtherStuff NVARCHAR(10)', #someValue)
This then makes sure that parameters for the dynamic SQL are passed through safely and the chances for injection attacks are reduced. It also improves the chances that the execution plan associated with the query will get reused.
personally, i just use a batch file and shell to sqlcmd for things like this. otherwise, building the sql in a stored proc (like you said) would work just fine. not sure why it would be "wrong" to do that.
best regards,
don
MSSQL has an OPENQUERY(dbname,statement) function where if the the server is linked, you specify it as the first parameter and it fires the statement against that server.
you could generate this openquery statement in a dynamic proc. and either it could fire the backup proc on each server, or you could execute the statement directly.
Do you use SSIS? If so you could try creating a couple ssis packages and try scheduling them,or executing them remotely.