Dynamic View name in Table valued function - sql

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?

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.

T-SQL Dynamically execute stored procedure

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

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 tables from UDF in SQL Server

how can i decide this problem?
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[GetDataById] ()
RETURNS INT
AS
BEGIN
DECLARE #query NVARCHAR(500)
DECLARE #j INT
SET #query=N'select * from catalog'
EXEC sp_executesql #query
RETURN #j
END
When I try to exec this one: select dbo.GetDataById()
I get an error message:
Only functions and extended stored procedures can be executed from within a function.
From this post by Erland Sommarskog, SQL Server MVP :
you cannot use dynamic SQL from
used-defined functions written in
T-SQL. This is because you are not
permitted do anything in a UDF that
could change the database state (as
the UDF may be invoked as part of a
query). Since you can do anything from
dynamic SQL, including updates, it is
obvious why dynamic SQL is not
permitted.
You can't use dynamically-created SQL from within a function. You have to use a stored procedure for that.
But in your case I don't see why you even put your query into a variable anyway.

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.