Return string with dynamic SQL - sql

I am using SQL Server 2008 and I have a variable #sqlFinal which is of type Varchar(500).
I fill the variable as the stored procedure runs. I want to dynamically return what is in the string to show the results
SELECT #sqlFinal = 'SELECT #Error_Return AS Final_Report'
--PRINT #sqlFinal
EXEC (#sqlFinal)
But I get the following error
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "#Error_Return".

I am assuming that #Error_Return is in the same scope as #SqlFinal?
If you just need to return the contents of #Error_Return, you can just execute this line:
SELECT #Error_Return as Final_Report
... making it a static SQL line rather than a dynamic one.
But if that's not acceptable, you may have to use sp_executeSQL instead. This allows you to pass variables to the line you're executing.
Declare #Error_Return VARCHAR(10)
Set #Error_return= 'Whatever'
exec sp_executesql N'SELECT #Error_Return as Final_Report', N'#Error_Return varchar(10)', #Error_Return

The EXEC() function creates a new execution scope. Variables, like #Error_Return, that are defined in the the current scope will not be available in the Exec() function. Look into sp_executesql instead.

Related

Passing a variable into sp_helptext

We want to dynamically pass variables into sp_helptext but because sp_helptext accept a variable passed into the colon; this is causing an error.
My query looks like so:
EXEC sp_helptext N'DatabaseName.dbo.SpName'; --- this works
DECLARE #spName VARCHAR(120) = 'spName'
EXEC sp_helptext N'DatabaseName.dbo.'+#spName+''
And the error:
Msg 102, Level 15, State 1, Line 53
Incorrect syntax near '+'.
The problem is that string operations are not supported for arguments.
This is easy enough to fix. Just do the string operations before the call:
DECLARE #spName VARCHAR(120) = 'spName';
DECLARE #fullName NVARCHAR(MAX) = N'DatabaseName.dbo.' + #spName;
EXEC sp_helptext #fullName;
This is for demonstration. If you are actually passing such values in, then you should be using QUOTENAME().

how evaluate an arithmetic expression within a SQL scalar function

i am trying to execute this scalar function and i tried a lot of approaches to achieve this but i get stuck
Create FUNCTION CalculateElementFunc()
RETURNS int
AS
BEGIN
DECLARE #ResultVar numeric(18,6)
DECLARE #eq nvarchar(MAX)
set #eq = '7.5/100*1258.236'
declare #expression nvarchar(max)
set #expression = #eq
declare #result int
declare #SQLString nvarchar(max)
Set #SQLString = N'Select #result = #expression'
exec sp_executesql #SQLString, N'#expression nvarchar(100)',
#expression,
#result = #result output
select #ResultVar = #result
if( #ResultVar <> ROUND( #ResultVar, 2 ,1))
set #ResultVar = cast( ROUND( #ResultVar, 2 ,1) + .01 as numeric(18,2))
RETURN #ResultVar
END
When i try to execute it
select dbo.CalculateElementFunc()
i get this error
Msg 557, Level 16, State 2, Line 1
Only functions and some extended stored procedures can be executed from within a function.
Please Advice
What you want to do is not recommended in SQL Server. First, it is really hard. As you have learned, a SQL Server function cannot execute dynamic SQL.
This is subtly in the documentation:
EXECUTE statements calling extended stored procedures.
exec and sp_executesql are not extended stored procedures.
What can you do? Here are some options:
Is a stored procedure instead of a UDF a possibility? Stored procedures can execute the dynamic SQL.
Can you get around the problem of expression evaluation? Perhaps dynamic SQL can be used one level up in your code.
You can execute an extended stored procedure that starts another transaction and executes the dynamic SQL. Think: really bad performance.
You can write a CLR extended function.
Limitations on SQL User Defined Functions:
Non-deterministic build in functions cannot be used in user defined functions. e.g. GETDATE() or RAND().
XML data type is not supported.
Dynamic SQL queries are not allowed.
User defined functions does not support any DML statements (INSERT, UPDATE, DELETE) unless it is performed on Table Variable.
We cannot make a call to the stored procedure. Only extended stored procedure can be called from function.
We cannot create Temporary tables inside UDFs.
It does not support Error Handling inside UDF. Although, we can handle errors (RAISEERROR, TRY-CATCH) for the statements which uses this function.
And it looks like you are using/calling a stored procedure inside your User Defined Function. It is not the expression that's bugging you, it's that stored procedure call.
Try to replace it with some logic to achieve your desired output.
Hope this is helpful. If it helps to solve your problem then don't forget to mark it as an answer.

Syntax error in sql exec count

declare #message int,#DBName varchar(50)
set #DBName ='AutoChip'
exec('select '+#message+'= count(*) from '+#DBname+'.[dbo].[Report List]')
print #message
Getting an error trying to print the count
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '='.
I will pass DBname dynamically, I am using a cursor
The variable name needs to be part of dynamic SQL you are creating, but it's shouldn't be concated with it.
For example, if your variable is of type varchar and has value as 'ERROR', resultant query will be
select ERROR= count(*) from YOURDBNAME.[dbo].[Report List]
so the correct one is below.
exec('select #message= count(*) from '+#DBname+'.[dbo].[Report List]')
You need to include variable declaration and initialization in dynamic sql. You cannot set a value of external variable inside a dynamic sql as the context of execution will be different.

Dynamic query inside a SQL scalar function

I want to invoke a dynamic query inside a Scalar function. I tried using EXEC and sp_executesql, but it is not found success. Then I went for OPENQUERY, But it do not accept dynamic parameters.
Here is my SQL code
DECLARE #query varchar(max) = 'SELECT COUNT('+#FromCol+') from '+#FromTable+' WHERE '+#FromCol+' IN (SELECT '+#ToCol+' FROM '+#ToTable+' WHERE userId = 0)'
INSERT INTO #TempResult([rowCount])
SELECT *
FROM OPENQUERY([GREEN\SQLEXPRESS], 'Exec [MyDB].[dbo].[testSP] '+[#FromCol]) as [OpenQuery]
Here, if possible can I execute dynamic query ie, #query or pass parameter to stored procedure testSP?

Dynamic Function Issue

I am trying to create some dynamic DDL to build a function and when I run it, it keeps giving me an error. I am not sure what I am doing wrong with the format....I have tried a lot of different things and now it is just out of curiousity that I want to understand how to get it to work. Any input is greatly appreciated.
CODE:
DECLARE #SQL nvarchar(max) =
'ALTER FUNCTION dbo.GetFiscalDate()
RETURNS DATETIME
AS
BEGIN
DECLARE #RESULT DATETIME
SELECT #RESULT = #FY
RETURN #RESULT;
END'
,#FY datetime = '01/01/2016'
,#ParamDef nvarchar(50) = N'#FY datetime'
exec sp_executesql #SQL,#ParamDef,#FY
Gives me this error:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'FUNCTION'.
Msg 178, Level 15, State 1, Line 7
A RETURN statement with a return value cannot be used in this context.
This Code however...works:
DECLARE
#FY nvarchar(10) = '01/01/2015'
,#SQL nvarchar(max)
Select #SQL =
'ALTER FUNCTION dbo.GetFiscalDate()
RETURNS DATETIME
AS
BEGIN
DECLARE #RESULT DATETIME
SELECT #RESULT = ' + #FY + '
RETURN #RESULT;
END'
exec sp_executesql #SQL
What am I missing with this when I want to pass in params instead of concatenating them with the statement?
As usual I greatly appreciate all input.
Thanks,
S
parameters are used in execution plans so that you can reuse the execution plan, not in DDL statements, use your 2nd approach
I don't see where in your string you're including a call to your function.
Whatever sql you put in your string should exec directly in a query window, and altering a function and then listing the params wouldn't do it. You have to exec the function with the params listed in their normal syntax.
Why not pass the #FY variable as a parameter into the function?
I'm not sure what you're trying to do, but I wouldn't expect the approach you've described above to work.