I have to set a dynamic sql query result to a variable. My sql query is :
DECLARE #ResultString NVARCHAR(MAX)
DECLARE #Qry NVARCHAR(MAX)
SET #Qry='SELECT Test FROM MTest22Dec WHERE ID = 1'
EXECUTE sp_executesql #Qry, N'#Result NVARCHAR(MAX) OUTPUT', #Result=#ResultString OUTPUT
PRINT #ResultString
But #ResultString is printing empty string although there is record in database table.
What is wrong in this query?
thanks
You need to assign the result of select to variable inside Dynamic statement.
Change you query like this.
DECLARE #Result NVARCHAR(MAX)
DECLARE #Qry NVARCHAR(MAX)
SET #Qry='SELECT #Result = Test FROM MTest22Dec WHERE ID = 1'
EXECUTE Sp_executesql #Qry, N'#Result NVARCHAR(MAX) OUTPUT', #Result OUTPUT
PRINT #Result
You have to set the output variable somewhere, eg.
SET #Qry='SELECT #Result = Test FROM MTest22Dec WHERE ID = 1'
Try this:
DECLARE #ResultString NVARCHAR(MAX)
DECLARE #Qry NVARCHAR(MAX)
SET #Qry='SELECT #ResultString = Test FROM MTest22Dec WHERE ID = 1'
EXECUTE sp_executesql #Qry, N'#ResultString NVARCHAR(MAX) OUTPUT', #ResultString OUTPUT
PRINT #ResultString
Try this :
Declare #Query NVARCHAR(100)
Declare #ResultString varchar(50)
set #Query =N'select #ResultString=Test from dbo.MTest22Dec where id = #id'
exec sp_executesql #Query, N'#id int,#ResultString varchar(20) output',
#id = 1,#ResultString=#ResultString output
print #ResultString
Related
I am trying to use a dynamic SQL statement in a stored procedure to filter a query depending on the input from a user. I am starting basic with just one parameter that needs to find matching forenames in the database.
CREATE PROCEDURE dbo.uspFilter
#FirstName varchar(100) = null,
#Debug bit = 1
AS
DECLARE #SQL nvarchar(max);
DECLARE #Params nvarchar(max);
DECLARE #Search nvarchar(300);
SELECT #Params = N'#FirstName varchar(300) = null'
SELECT #SQL = N'SELECT * FROM Table WHERE 1=1'
IF #FirstName IS NOT NULL
SELECT #Search = N'#FirstName' + N'%'''
SELECT #SQL = #SQL + N' AND Forename LIKE ''' + #Search
IF #Debug = 1
#PRINT #SQL
EXEC sp_executeSQL #SQL, #Params, #FirstName = #FirstName;
GO
EXEC dbo.uspFilter #FirstName = 'Test', #Debug = 1;
GO
The output of the debug statement looks correct but it is not returning any results:
SELECT * FROM Table WHERE 1=1 AND Forename LIKE '#FirstName%'
EDIT: This is a meant to be a trimmed down version of what I am looking for - I will be using multiple parameters with different search criteria.
This is how you need to do it:
CREATE PROCEDURE dbo.uspFilter
#Search varchar(300) = null,
#Debug bit = 1
AS
DECLARE #SQL nvarchar(max);
DECLARE #Params nvarchar(max);
SELECT #Params = N'#FirstName varchar(300)';
SELECT #SQL = N'SELECT * FROM [Table]';
IF #FirstName IS NOT NULL BEGIN
SET #SQL = #SQL + N' WHERE Forename LIKE #FirstName + ''%'';';
END ELSE BEGIN
SET #SQL = #SQL + N';';
END
IF #Debug = 1
PRINT #SQL;
EXEC sp_executeSQL #SQL, #Params, #FirstName = #Search;
GO
EXEC dbo.uspFilter #Search = 'Steve', #Debug = 1;
Note that although Crowcoder's comment about SQL Injection is important, you can write dynamic SQL that doesn't allow for Injection. Such as the above.
Edit: Couple of slight corrections.
CREATE PROCEDURE dbo.uspFilter
#Search varchar(300) = null,
#Debug bit = 1
AS
DECLARE #SQL nvarchar(max);
DECLARE #Params nvarchar(max);
SELECT #Params = N'#FirstName varchar(300)';
SELECT #SQL = N'SELECT * FROM [YourTable]';
IF #Search IS NOT NULL BEGIN
SET #SQL = #SQL + N' WHERE Forename LIKE #FirstName;';
END ELSE BEGIN
SET #SQL = #SQL + N';';
END
IF #Debug = 1
PRINT #SQL;
EXEC sp_executeSQL #SQL, #Params, #FirstName = #Search;
GO
EXEC dbo.uspFilter #Search = 'Rameshbhai%', #Debug = 1;
go
pass parameter with wildcard values like 'searchtext%'
You can also apply dynamic where condition as below without make dynamic query, please have look at below sample example. You can join other filter by applying AND where clause with below example.
Declare #firstName VARCHAR(50)='sa'
SELECT
*
FROM Table
WHERE
(
(Forename LIKE '%'+#firstName+'%' AND #firstName!='')
OR
(#firstName='')
)
declare #sql as nvarchar(500)=''
set #sql='
declare #N4 as int = 1
declare #ms as nvarchar(100) = concat(''ms'', convert(nvarchar(10), #N4))
select #ms
'
exec #sql
I want output as ms1.
DECLARE #SQL AS NVARCHAR(500)=''
SET #sql='
while (#i <10)
begin
PRINT (''MS_''+#I)
set #i=#i+1
end
'
EXEC(#SQL)
not generating value for #i
i want to put this code in while loop as I want to access ms1 to ms10
Use sp_executesql which supports ouput params
DECLARE #MS VARCHAR(50)
exec sp_executesql N'declare #N4 as int = 1;
SELECT #MS= concat(''ms'', convert(nvarchar(10), #N4))',
N'#MS VARCHAR(50) output', #MS output;
SELECT #MS
Yes, you can use and for that you need to use sp_executesql like this -
Declare #sql as nvarchar(500)='', #Params NVARCHAR(500),
#N4 Int = 1, #ms nvarchar(100)
SET #Params = '#N4 Int, #ms nvarchar(100) OUTPUT'
set #sql= N'SELECT #ms = concat(''ms'', convert(nvarchar(10), #N4))'
EXEC SP_EXECUTESQL #sql, #Params, #N4 = #N4, #ms = #ms OUTPUT
SELECT #ms
Use While statement and string concatenation to get your result :
DECLARE #StartValue INT = 1
DECLARE #EndValue INT = 10
DECLARE #Query VARCHAR(500) = ''
WHILE #StartValue < #EndValue
BEGIN
SET #Query = #Query + 'sms_' + CAST(#StartValue AS VARCHAR) + ','
SET #StartValue = #StartValue + 1
END
SELECT Query
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
I need to execute a procedure that is encrypted and get the return(That is a XML) and add to a variable. I try with sp_executesql but don't sucess.
here's what a try:
declare #str nvarchar(max)
select #str ='';
dECLARE #Params NVARCHAR(max)
DECLARE #result varchar(max)
SET #Params = N'#resultout varchar(max) OUTPUT'
select #str ='select #resultout = MyProcedure #pageIndex=0,#ascDesc=N''ASC'',#culture=N''pt-br'''
EXEC sp_executesql #str,
#Params,
#resultout=#result OUTPUT
select #result
What is wrong?
Here is what I have so far. I want to store the query result into an int variable but I get null so far. After execute, both #query and #countrow are both null. Any suggestion would be great.
SET #query = N'select #countrow=count(*) from ' + #tablename
EXECUTE sp_executesql #query
DECLARE #i INT, #sql NVARCHAR(512), #tablename varchar(200) = 'tbl'
SET #sql = N'SELECT #i = COUNT(*) FROM ' + #tablename
EXEC sp_executesql
#query = #sql,
#params = N'#i INT OUTPUT',
#i = #i OUTPUT
PRINT #i
Take a look at SQL Fiddle
You need to use the OUTPUT keyword, similar to this:
declare #query nvarchar(max)
declare #countrow int
declare #tablename varchar(50)
SET #query = N'select #cnt=count(*) from ' + #tablename
EXECUTE sp_executesql #query, N'#cnt int OUTPUT', #cnt=#countrow OUTPUT
select #countrow as countrow -- to get the result