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

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

Related

Must declare scalar variable in sql server dynamic sql

I am having problems running sql server stored procedure. I using a dynamic sql.
I get the error "Must declare the scalar variable "#EmployeeId".
SQL QUERY
ALTER PROCEDURE [dbo].[GetLeaveDays] -- Add the parameters for the stored
procedure here
#LeaveType varchar(5000),
#AdminId int,
#EmployeeId int
AS
BEGIN
SET NOCOUNT ON;
DECLARE
#queryString nvarchar(MAX);
SET #queryString = 'SELECT ' + #LeaveType + ' FROM CompulsoryLeave WHERE
AdminId = #AdminId AND Id=(SELECT LeaveStructureId FROM Employee WHERE
Id=#EmployeeId)';
EXECUTE sp_executesql #queryString,
N'#AdminId int',
N'#EmployeeId int',
#AdminId = #AdminId,
#EmployeeId=#EmployeeId
END
The second sp_executesql parameter should be a single string with all parameter definitions. Try:
EXECUTE sp_executesql #queryString,
N'#AdminId int, #EmployeeId int',
#AdminId = #AdminId,
#EmployeeId = #EmployeeId;

How to pass an output variable in dynamic sql query

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

Error when using OUTPUT parameter with sp_execute

I'm having a problem with dynamic SQL and reduced my code to this simplest possible example. Why does this:
DECLARE #Statement NVARCHAR(1000), #Name SYSNAME;
SET #Statement = N'SELECT TOP 1 #Name = name from sys.objects';
EXEC sp_execute #Statement, N'#Name SYSNAME OUTPUT', #Name OUTPUT;
Get me this:
Msg 214, Level 16, State 2, Procedure sp_execute, Line 1
Procedure expects parameter '#handle' of type 'int'.
What is the correct syntax?
I also tried:
DECLARE #Statement NVARCHAR(1000), #Name SYSNAME;
SET #Statement = N'SELECT TOP 1 #NameOUT = name from sys.objects';
EXEC sp_execute #Statement, N'#NameOUT SYSNAME OUTPUT', #NameOUT = #Name OUTPUT;
But had the same errror.
I think you meant to use sp_executesql instead, since you're executing a SQL string. Compare the documentation: sp_execute vs. sp_executesql.

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