T-SQL Dynamically execute stored procedure - sql

I have a logging function in T-SQl similiar to this:
CREATE PROCEDURE [logging]
#PROCEDURE VARCHAR(50),
#MESSAGE VARCHAR(MAX)
AS
BEGIN
PRINT #MESSAGE
END;
GO
I am able to call it like this:
execute logging N'procedure_i_am_in', N'log_message';
As my stored procedure names are a bit long winded, I want to write an alias or an inline function or so, to call the logging procedure for me, with the current procedure. Something like this (which is broken):
declare #_log varchar(max)
set #_log = 'execute logging N''procedure_i_am_in'', '
execute #_log N'MESSAGE!'
And i would put that alias at the top of each procedure.
What are your thoughts?

Quite simple
CREATE PROCEDURE [logging]
#PROCID int,,
#MESSAGE VARCHAR(MAX)
-- allows resolution of #PROCID in some circumstances
-- eg nested calls, no direct permission on inner proc
WITH EXECUTE AS OWNER
AS
BEGIN
-- you are using schemas, right?
PRINT OBJECT_SCHEMA_NAME(#PROCID) + '.' + OBJECT_NAME(#PROCID);
PRINT #MESSAGE
END;
GO
Then
execute logging ##PROCID, N'log_message';
MSDN on OBJECT_SCHEMA_NAME and ##PROCID
Edit:
Beware of logging into tables during transactions. On rollback, you'll lose the log data

More trouble than it's worth, but
it would be
Set #_log = 'exec ....N' + 'MESSAGE!'
Exec (#log)
So not a lot of use.
Personally I'sd just rename the SP, or at a push use a tersely named function. Building strings and exec'ing them is an only if you must admin style facility IMHO

Related

Selecting from stored procedure output

I am trying to explore the possibility of selecting from a stored procedure.
Something like this
SELECT name
FROM exec msdb..sp_help_job
WHERE name = 'SampleJob'
I understand SQL Server - SELECT FROM stored procedure that a user-defined function or view can be used, but these are not options for me.
Reason being I am not able to run the following SQL statement due to permission limitations on AWS-RDS.
SELECT name as Jobs
FROM msdb..sysjobs
This leaves me with no choice but to use msdb..sp_help_job.
What I am ultimately trying to achieve is this "If job is not created, then run create job script". The reason I need to select from the stored procedure is to see if the job exists.
Appreciate any advice / directions.
If you want to create something, but are concerned that it might already exist, then use try/catch blocks.
begin try
exec dbo.sp_add_job . . .
end try
begin catch
print 'Error encountered . . . job probably already exists'
end catch;
To be honest, I haven't done this with jobs/job steps. However, this is one way of re-creating tables, views, and so on.
According to the documentation for sp_help_job on MSDN this stored procedure has a #job_name parameter and a simple return code (0 = success or 1 = failure).
If you set the #job_name parameter on your call to sp_help_job and get the return code you should be able to test the value of the return code to accomplish what you want.
Something like this should work:
DECLARE #return_value int
EXEC #return_value = msdb..sp_help_job #job_name = 'MyJobName'
-- #return_value = 1 means the specified #job_name does not exist
IF #return_value = 1
BEGIN
-- run create job script
END

stored procedure receiving DB name to work with

I am looking to write a stored procedure which received a database name along with other parameters, and the stored procedure needs to work on the Database which it received
any thoughts please
Something like the following should work, as long as correct permissions are setup:
CREATE PROCEDURE dbo.sptest
#DB VARCHAR(50)
AS
BEGIN
DECLARE #sqlstmt VARCHAR(MAX)
SET #sqlstmt='SELECT TOP 10 * FROM ' + #DB + '.dbo.YourTableName'
sp_executesql #sqlstmt
END
GO
As mentioned, be very careful when using dynamic SQL like this- only use with trusted sources because of the ability to wreck havoc on your DB. At a minimum, you should add some checking of the value of #DB passed in to make sure it matches a limited list of database names that it will work with.

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.
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.

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.