Get SQL result into variable - sql

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

Related

How to get value by dynamic field Name using sql select query

I am passing dynamic column name base that column name to get the value and below i my table
Table_CandidateInfo
Id Name Age City
1 Mazhar 30 Gulbarga
20 Khan 29 Bidar
Example1
Declare #ColumnName varchar(100), #Id int
set #ColumnName='Age'
set #Id=20
select * from Table_CandidateInfo where ID=#Id and
I am not able to pass ColumnName with and query because column name is dynamic pass by code. My output should be
29
Example2: If my #ColumnName='City' and #Id=20 then output should be like below
Bidar
I think what you are actually after is the below:
DECLARE #ColumnName sysname, #Id int;
SET #Id = 29;
SET #ColumnName = N'Age';
DECLARE #SQL nvarchar(MAX);
SET #SQL = N'SELECT ' + QUOTENAME(#ColumnName) + N' FROM dbo.Table_CandidateInfo WHERE Id = #Id;';
--PRINT #SQL; --Your debugging friend
EXEC sp_executesql #SQL, N'#Id int', #Id = #Id;
Alas, you cannot pass identifiers as parameters. You need to use dynamic SQL:
declare #columnName varchar(100);
declare #Id int;
set #ColumnName = 'Age' ;
set #Id = 20;
declare #sql nvarchar(max);
set #sql = '
select *
from Table_CandidateInfo
where [columnName] = #Id';
select #sql = replace(#sql, '[columnName]', quotename(#columnName));
exec sp_executesql #sql,
N'#id int',
#id=#id;

Issue with using like with a wildcard in dynamic SQL statement

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='')
)

I want to use dynamic variable that is declared within dynamic SQL

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

Set EXECUTE sp_executesql result into a variable in sql

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

Conversion failed while converting nvarchar value to datatype int

I want to get the values of #sql to p.
But while conversion it says that "Conversion failed when converting the nvarchar value 'select sum(stock) from[Hard disk]' to data type int."
declare #tname varchar(10);
declare #p int
declare #i int
declare #sql nvarchar(max);
set #tname = 'Hard disk';
set #sql = 'select sum(stock) from' + '[' + #tname + ']'
exec (#sql)
print #sql
select #p = convert(int,#sql)
print #p
What i want is to assign the result of the query #SQL in integer variable #p..
One way to do it is do it all in the dynamic sql.
declare #tname varchar(10);
declare #p int
declare #i int
declare #sql nvarchar(max);
set #tname = 'Hard disk';
set #sql =
'DECLARE #Result AS INT
select #Result = sum(stock) from' + '[' + #tname + ']
PRINT #Result'
exec (#sql)
The other way would be creating an output param.
DECLARE #tname VARCHAR(50)
DECLARE #SQLString NVARCHAR(500)
DECLARE #ParmDefinition NVARCHAR(500)
DECLARE #Result INT
SET #tname = 'Hard disk';
SET #SQLString = N'SELECT #Result = sum(stock)
FROM ' + QUOTENAME( #tname )
SET #ParmDefinition = N'#Result INT OUTPUT'
EXECUTE sp_executesql
#SQLString,
#ParmDefinition,
#Result=#Result OUTPUT
PRINT #Result
You better use QUOTENAME for embrasing the table name with the brackets, as it is more native.
declare #p int;
EXEC SP_EXECUTESQL N'select #p = sum(stock) from '[' + #tname + ']',N'#p int OUTPUT',#p OUTPUT;
select #p