How to pass an output variable in dynamic sql query - sql

I was reviewing a stored procedure where I found piece of code below. Looking at the code, my perception is that we are creating a variable named #QuestionInclude and passing its value in dynamic sql statement. But how this code is working?
This is something strage and new to me.
declare #QuestionInclude varchar(10)
select #sqln = 'select #QuestionInclude = 1 from ##Stg_Prelim'
exec sp_executesql #sqln,N'#QuestionInclude varchar(10) output',#QuestionInclude output

may be this will help you
http://msdn.microsoft.com/en-us/library/ms188001.aspx
procedure sp_executesql have parameters #stmt, which is actual statement to run, #params - declaration of parameters, and then all parameters declared in #params
It's also better to pass parameters by names
declare #QuestionInclude varchar(10), #stmt nvarchar(max), #params nvarchar(max)
select #stmt = 'select #QuestionInclude = 1 from ##Stg_Prelim'
select #params = '#QuestionInclude varchar(10) output'
exec sp_executesql
#stmt = #stmt,
#params = #params,
#QuestionInclude = #QuestionInclude output

Related

Error in dynamic execute with local variable

I'm getting the error :
Procedure expects parameter '#params' of type 'ntext/nchar/nvarchar'
for the following execute statement. I'm a little confused with this, after reading several posts on the website,
I came to understand that I would need to pass #val as a variable since exec will execute the command as-is.
declare #val varchar(max);
declare #query nvarchar(max);
set #query = 'set #val = (select ' + #cols + ' from temp where loan_number = ''72'')'
exec sp_executesql #query, '#val varchar(max) output', #val output
Conversely, if I executed the exec as a non-dynamic query as just exec(#query), I get the error
Must declare the scalar variable "#val".
IF the statement "Should the output of the query be a 1x1 table since I" is true, then you need to use a SELECT to set the value:
DECLARE #val varchar(MAX);
DECALRE #query nvarchar(MAX);
SET #query = N'SELECT #val = ' + QUOTENAME(#cols) + N' FROM temp WHERE loan_number = ''72'');';
EXEC sp_executesql #query, N'#val varchar(MAX) OUTPUT', #val OUTPUT;
The fact that you have a variable called #cols implies that the variable will hold the names of many columns, not one.

SELECT FROM #random_table SQL Server 2008 R2

I'm having an issue with the following code:
DECLARE #table varchar(50), #value int
SET #table = 'randomTable'
EXEC('SELECT #value = exercicio FROM '+#table+' WHERE cod = 2')
I need to do a couple of operations like that one above in some random tables. I want to select a value and store in a variable previously declared. But when I tried to execute that code, I received the following message:
Must declare the scalar variable "#value".
I'm out of ideas. Any suggestions?
The #value variable is outside the scope of the dynamic SQL statement. You'll need to return the value as an output parameter:
DECLARE
#table nvarchar(251) = N'dbo.randomTable'
, #SQL nvarchar(MAX)
, #value int;
SET #SQL = N'SELECT #value = exercicio FROM '+#table+N' WHERE cod=2';
EXEC sp_executesql #SQL, N'#value int OUTPUT', #value OUT;

sql server save result of exec(#query) in string

I have a query which returns a single result.
#query='select name from studtable where id=1'
How should I write query so that result is saved in string and #result contains result.
#result=exec(#query)
To execute a string, we recommend that you use the sp_executesql stored procedure
instead of the EXECUTE statement. Because this stored procedure supports parameter
substitution, sp_executesql is more versatile than EXECUTE; and because
sp_executesql generates execution plans that are more likely to be reused by SQL
Server, sp_executesql is more efficient than EXECUTE.
Read more here:http://technet.microsoft.com/en-us/library/ms175170(v=sql.105).aspx
So you can write as"
DECLARE #SQLString NVARCHAR(500)
DECLARE #ParmDefinition NVARCHAR(500)
DECLARE #IntVariable INT
DECLARE #name varchar(30)
SET #SQLString = N'SELECT #nameOUT = name
from studtable where id=#id'
SET #ParmDefinition = N'#id tinyint,
#nameOUT varchar(30) OUTPUT'
SET #IntVariable = 1
EXECUTE sp_executesql
#SQLString,
#ParmDefinition,
#id = #IntVariable,
#nameOUT=#name OUTPUT
SELECT #name
You can do something like below to store the result using sp_executesql with output parameter. Observed from here Assign result of dynamic sql to variable
declare #ret int
set #ret = 0
set #query='select name from studtable where id=1'
exec sp_executesql #query, N'#var int out', #ret out
select #ret

Selecting from a table where the name is passed as a variable

I am trying to write a simple stored proc which takes three arguments 'database name one', 'database name two' and 'table name'. The sql will then perform a row count for the defined table in each database and store it.
Working on it piecemeal I have hit the first problem in that you can't do
select * from #tablename
I know you can use dynamic sql with the exec command but this is not ideal as I can't return values.
The following example looks like it should work but doesn't.
declare #tablename as nvarchar(500)
declare #sqlstring as nvarchar(500)
declare #parmdefinition as nvarchar(500)
declare #numrows as bigint
set #tablename = N'dummy_customer'
set #parmdefinition = N'#tablenameIN nvarchar(500), #numrowsOUT as bigint OUTPUT'
select #sqlstring = 'select #numrowsOUT = count(*) from #tablenameIN'
select #sqlstring
exec sp_executesql #sqlstring, #parmdefinition, #tablenameIN = #tablename, #numrowsOUT = #numrows OUTPUT
select #numrows
The error message given is
Msg 1087, Level 16, State 1, Line 1
Must declare the table variable "#tablenameIN".
Currently using SQL Server 2008 SP2.
Edit:
We're doing this because we are doing a migration and the customer wants a report which shows the row count for each table in the source and destination database. As there are many tables being able to use sp_MSForEachTable to call the stored proc seems ideal.
Edit:
The final solution for future reference is
declare #tablename as nvarchar(500)
declare #sqlstring as nvarchar(500)
declare #parmdefinition as nvarchar(500)
declare #numrows as bigint
set #tablename = N'dummy_customers'
set #parmdefinition = N'#tablename nvarchar(500), #numrowsOUT as bigint OUTPUT'
select #sqlstring = 'select #numrowsOUT = count(*) from ' + quotename(#tablename)
exec sp_executesql #sqlstring, #parmdefinition, #tablename = #tablename, #numrowsOUT = #numrows OUTPUT
select #numrows
You'd have to use dynamic sql, and concatenate the table name into the SQL string to then execute via sp_executsql:
select #sqlstring = 'select #numrowsOUT = count(*) from ' + QUOTENAME(#tablename)
EXECUTE sp_executesql ....

how to pass variables this in dynamic query in sql

i using the dynamic query to pass the variables
select a.TableName, COUNT(a.columnvalue) as '+'count'+' from Settings a
where a.ColumnValue in ('+ #columnvalue +') and a.Value in (' + #value +')
the #columnvalues = 'a','b','c'
#value ='comm(,)','con(:)'
how to pass this in dynamic query
any idea???
I would use the sp_executesql command.
Some more documentation is here: http://msdn.microsoft.com/en-us/library/ms188001.aspx
Basically, you define a sql query, and parameter list, and then pass those in along with your actual parameters into that method.
So, something like this (real basic)
CREATE PROCEDURE dbo.yourProc
#customerId INT
AS
DECLARE #sql NVARCHAR(1000)
SET #sql = 'SELECT * FROM Customers WHERE CustomerId = #customerId'
DECLARE #params NVARCHAR(1000)
SET #params = '#customerId INT'
EXEC dbo.sp_executesql #sql, #params, #customerId