How to use Pass comma separated string in dynamic query in SQL - sql

I have a function which will return integer values from comma delimited string , It takes two parameters (#string nvarchar(4000), #delimiter char(1)). So the problem is if I am using this function inside a dynamic query I am getting error , here is query
declare #ProductIDs varchar(11)
declare #SQL varchar(max)
set #ProductIDs='1,2,3,4'
declare #query varchar(max)
--set #query= #ProductIDs +','+#Delimiter
SELECT #SQL = 'SELECT val FROM dbo.[fnDelimitedStringToTable]('+ #ProductIDs +' , '','')'
Exec(#SQL)
I am getting error Procedure or function dbo.fnDelimitedStringToTable has too many arguments specified.

When you build a dynamic SQL like that, you need to wrap your parameter in double quote ''
declare #ProductIDs varchar(11)
declare #SQL varchar(max)
set #ProductIDs='1,2,3,4'
declare #query varchar(max)
--set #query= #ProductIDs +','+#Delimiter
SELECT #SQL = 'SELECT val FROM dbo.[fnDelimitedStringToTable]('''+ #ProductIDs +''' , '','')'
Exec(#SQL)
This way the SQL statement will be:
SELECT val FROM dbo.[fnDelimitedStringToTable]('1,2,3,4' , '','')
and not:
SELECT val FROM dbo.[fnDelimitedStringToTable](1,2,3,4 , '','')

Use sp_executesql instead. In this case you can pass arguments as parameters.
DECLARE #SQL nvarchar(max)
DECLARE #ParmDef nvarchar(1000)
DECLARE #ArgProductIDs nvarchar(100)
DECLARE #Arg2 nvarchar(100)
DECLARE #Arg3 nvarchar(100)
SET #SQL = N'SELECT val
FROM dbo.[fnDelimitedStringToTable](#ProductIDs, #Param2, #Param3)';
SET #ParmDef = N'#ProductIDs nvarchar(100),
#Param2 nvarchar(100),
#Param3 nvarchar(100)';
SET #Arg1 = N'1,2,3,4';
SET #Arg2 = N'';
SET #Arg3 = N'';
EXEC sp_executesql #SQL, #ParmDef,
#ProductIDs = #ArgProductIDs, #Param2 = #Arg2, , #Param3 = #Arg3

Related

How to get dynamic SQL query output into declared variable in SQL Server? [duplicate]

I have a piece of dynamic SQL I need to execute, I then need to store the result into a variable.
I know I can use sp_executesql but can't find clear examples around about how to do this.
If you have OUTPUT parameters you can do
DECLARE #retval int
DECLARE #sSQL nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
DECLARE #tablename nvarchar(50)
SELECT #tablename = N'products'
SELECT #sSQL = N'SELECT #retvalOUT = MAX(ID) FROM ' + #tablename;
SET #ParmDefinition = N'#retvalOUT int OUTPUT';
EXEC sp_executesql #sSQL, #ParmDefinition, #retvalOUT=#retval OUTPUT;
SELECT #retval;
But if you don't, and can not modify the SP:
-- Assuming that your SP return 1 value
create table #temptable (ID int null)
insert into #temptable exec mysp 'Value1', 'Value2'
select * from #temptable
Not pretty, but works.
DECLARE #vi INT
DECLARE #vQuery NVARCHAR(1000)
SET #vQuery = N'SELECT #vi= COUNT(*) FROM <TableName>'
EXEC SP_EXECUTESQL
#Query = #vQuery
, #Params = N'#vi INT OUTPUT'
, #vi = #vi OUTPUT
SELECT #vi
DECLARE #tab AS TABLE (col1 VARCHAR(10), col2 varchar(10))
INSERT into #tab EXECUTE sp_executesql N'
SELECT 1 AS col1, 2 AS col2
UNION ALL
SELECT 1 AS col1, 2 AS col2
UNION ALL
SELECT 1 AS col1, 2 AS col2'
SELECT * FROM #tab
Return values are generally not used to "return" a result but to return success (0) or an error number (1-65K). The above all seem to indicate that sp_executesql does not return a value, which is not correct. sp_executesql will return 0 for success and any other number for failure.
In the below, #i will return 2727
DECLARE #s NVARCHAR(500)
DECLARE #i INT;
SET #s = 'USE [Blah]; UPDATE STATISTICS [dbo].[TableName] [NonExistantStatisticsName];';
EXEC #i = sys.sp_executesql #s
SELECT #i AS 'Blah'
SSMS will show this
Msg 2727, Level 11, State 1, Line 1
Cannot find index 'NonExistantStaticsName'.
If you want to return more than 1 value use this:
DECLARE #sqlstatement2 NVARCHAR(MAX);
DECLARE #retText NVARCHAR(MAX);
DECLARE #ParmDefinition NVARCHAR(MAX);
DECLARE #retIndex INT = 0;
SELECT #sqlstatement = 'SELECT #retIndexOUT=column1 #retTextOUT=column2 FROM XXX WHERE bla bla';
SET #ParmDefinition = N'#retIndexOUT INT OUTPUT, #retTextOUT NVARCHAR(MAX) OUTPUT';
exec sp_executesql #sqlstatement, #ParmDefinition, #retIndexOUT=#retIndex OUTPUT, #retTextOUT=#retText OUTPUT;
returned values are in #retIndex and #retText
Declare #variable int
Exec #variable = proc_name
DECLARE #ValueTable TABLE
(
Value VARCHAR (100)
)
SELECT #sql = N'SELECT SRS_SizeSetDetails.'+#COLUMN_NAME+' FROM SRS_SizeSetDetails WHERE FSizeID = '''+#FSizeID+''' AND SRS_SizeSetID = '''+#SRS_SizeSetID+'''';
INSERT INTO #ValueTable
EXEC sp_executesql #sql;
SET #Value='';
SET #Value = (SELECT TOP 1 Value FROM #ValueTable)
DELETE FROM #ValueTable
This worked for me:
DECLARE #SQL NVARCHAR(4000)
DECLARE #tbl Table (
Id int,
Account varchar(50),
Amount int
)
-- Lots of code to Create my dynamic sql statement
insert into #tbl EXEC sp_executesql #SQL
select * from #tbl
Here's something you can try
DECLARE #SqlStatement NVARCHAR(MAX) = ''
,#result XML
,#DatabaseName VARCHAR(100)
,#SchemaName VARCHAR(10)
,#ObjectName VARCHAR(200);
SELECT #DatabaseName = 'some database'
,#SchemaName = 'some schema'
,#ObjectName = 'some object (Table/View)'
SET #SqlStatement = '
SELECT #result = CONVERT(XML,
STUFF( ( SELECT *
FROM
(
SELECT TOP(100)
*
FROM ' + QUOTENAME(#DatabaseName) +'.'+ QUOTENAME(#SchemaName) +'.' + QUOTENAME(#ObjectName) + '
) AS A1
FOR XML PATH(''row''), ELEMENTS, ROOT(''recordset'')
), 1, 0, '''')
)
';
EXEC sp_executesql #SqlStatement,N'#result XML OUTPUT', #result = #result OUTPUT;
SELECT DISTINCT
QUOTENAME(r.value('fn:local-name(.)', 'VARCHAR(200)')) AS ColumnName
FROM #result.nodes('//recordset/*/*') AS records(r)
ORDER BY ColumnName
This was a long time ago, so not sure if this is still needed, but you could use ##ROWCOUNT variable to see how many rows were affected with the previous sql statement.
This is helpful when for example you construct a dynamic Update statement and run it with exec. ##ROWCOUNT would show how many rows were updated.
Here is the definition

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

How to pass variable/parameter as a datatype?

I would like to be able to change my datatypes and other values as a variable or as a parameter so that it could be changed and passed easily.
declare #datatype nvarchar(20) = 'datetime'
declare #inputvalue nvarchar(20) = '2015-10-21'
declare #variable #datatype = #inputvalue
exec spStoredProcedure #StoredProcedureParam = #variable
You would need to use dynamic sql inside your stored procedure for it, something like ....
declare #datatype nvarchar(20) = 'datetime'
declare #inputvalue nvarchar(20) = '2015-10-21'
-- Inside your proc you would do something like.....
Declare #Sql NVARCHAR(MAX);
SET #Sql = N' Declare #variable '+ QUOTENAME(#datatype) + N' = #inputvalue '
+ N' Select #variable AS VariableValue'
Exec sp_executesql #Sql
,N'#inputvalue nvarchar(20)'
,#inputvalue

Stored Procedure giving error

I'm trying to use a stored procedure to display the results of a table. The stored procedure is giving the error 'Procedure expects parameter '#parameters' of type 'ntext/nchar/nvarchar'
ALTER PROCEDURE COMNODE_PROC_SearchProduct --'','GUN',''
#PRODUCTID INT = NULL,
#PRODUCT_NAME VARCHAR(500) = NULL,
#PRODUCT_POINTS INT = NULL
AS
BEGIN
SET NOCOUNT ON;
Declare #SQLQuery AS NVarchar(MAX)
Declare #ParamDefinition AS NVarchar(MAX)
Set #ParamDefinition = '#ID INT,
#NAME VARCHAR(500),
#POINTS INT'
Set #SQLQuery = 'SELECT PRODUCT_ID,PRODUCT_NAME,PRODUCT_REDEEM_POINTS FROM TBL_REDEEM_PRODUCT WHERE (1 = 1)';
If #PRODUCTID Is Not Null
Set #SQLQuery = #SQLQuery + ' And (PRODUCT_ID ='+CAST(#PRODUCTID AS VARCHAR(500) )
If #PRODUCT_NAME Is Not Null
Set #SQLQuery = #SQLQuery + ' And (PRODUCT_NAME =' + CAST(#PRODUCT_NAME AS VARCHAR(500) )
If #PRODUCT_POINTS Is Not Null
Set #SQLQuery = #SQLQuery + ' And (PRODUCT_REDEEM_POINTS ='+ CAST(#PRODUCT_POINTS AS VARCHAR(500))
Execute sp_Executesql #SQLQuery,
#ID = #PRODUCTID ,
#NAME = #PRODUCT_NAME ,
#POINTS = #PRODUCT_POINTS;
END
You need to pass in the parameter definition to sp_executesql, see: https://msdn.microsoft.com/en-us/library/ms188001.aspx
Execute sp_Executesql #SQLQuery,
#ParamDefinition,
#ID = #PRODUCTID ,
#NAME = #PRODUCT_NAME ,
#POINTS = #PRODUCT_POINTS;
One of the main reasons you would want to use sp_executesql so do not have to concatenate variables, have you can be protected from sql-injection attack using the parameterised query.
You concatenating parameters just kill the purpose and makes your query vulnerable to sql-injection . See below the proper use of dynamic sql the safe way.
ALTER PROCEDURE COMNODE_PROC_SearchProduct --'','GUN',''
#PRODUCTID INT = NULL,
#PRODUCT_NAME VARCHAR(500) = NULL,
#PRODUCT_POINTS INT = NULL
AS
BEGIN
SET NOCOUNT ON;
Declare #SQLQuery AS NVarchar(MAX);
Declare #ParamDefinition AS NVarchar(MAX);
Set #ParamDefinition = N'#ID INT, #NAME VARCHAR(500), #POINTS INT';
-- A much cleaner way to write this would be...
Set #SQLQuery = N'SELECT PRODUCT_ID,PRODUCT_NAME,PRODUCT_REDEEM_POINTS
FROM TBL_REDEEM_PRODUCT
WHERE (1 = 1)'
+ CASE WHEN #PRODUCTID Is Not Null
THEN N' And PRODUCT_ID = #ID ' ELSE N' ' END
+ CASE WHEN #PRODUCT_NAME Is Not Null
THEN N' And PRODUCT_NAME = #NAME ' ELSE N' ' END
+ CASE WHEN #PRODUCT_POINTS Is Not Null
THEN N' And PRODUCT_REDEEM_POINTS = #POINTS' ELSE N' ' END
Execute sp_Executesql #SQLQuery
,#ParamDefinition --<-- this was missing
,#ID = #PRODUCTID
,#NAME = #PRODUCT_NAME
,#POINTS = #PRODUCT_POINTS;
END

Can I use variable in condition statement as value with where condition that test that value

I have the following stored procedure:
ALTER proc [dbo].[insertperoll] #name nvarchar(50) , #snum int , #gnum int
as
DECLARE #value nvarchar(10)
SET #value = 's'+CONVERT(nvarchar(50),#snum)
DECLARE #sqlText nvarchar(1000);
DECLARE #sqlText2 nvarchar(1000);
DECLARE #sqlText3 nvarchar(1000);
declare #g nvarchar(50) = '''g1'''
SET #sqlText = N'SELECT ' + #value + N' FROM dbo.GrideBtable'
SET #sqlText2 = ' where Gnumber = '+#g --here is the problem it error invalid column name -- the #g is value from the table condition
set #sqlText3 = #sqlText+#sqlText2
Exec (#sqlText3) -- here how can i save the result of the exec into varibale
declare #sal nvarchar(50) = #sqlText3
insert employ (name,Snumber,Gnumber,Salary) values(#name,#snum,#gnum,#sal)
QUESTION: How to put in condition variable gets value from the table when i exec it it think that the #g is column but its not its a value from the table to test it so i display one value after the exec the other QUESTION is how to save the result from the exec in variable and then use that value
I'm using SQL Server 2008 (9.0 RTM)
This will be a stored procedure
Thanks in advance
Not sure why you would go through all the loops to insert into the table where you can have a simple insert query like ..
ALTER PROC dbo.[insertperoll] #name nvarchar(50) , #snum int , #gnum int
AS
insert employ (name, Snumber, Gnumber, Salary)
select #name
, #sum
, #gnum
, case when #snum = 1 then s1
when #snum = 2 then s2
when #snum = 3 then s3
when #snum = 4 then s4
end as Salary
from dbo.GrideBtable
where Gnumber = #gnum
If your intent is to have the proc retrieve a salary value from a column determined from the parameter snum and then make an insert into employ using the values passed as parameters and the salary retrieved I think you could refactor your procedure to this:
CREATE proc [dbo].[insertperoll] #name nvarchar(50) , #snum int , #gnum int AS
DECLARE #g NVARCHAR(50) = 'g1'
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'INSERT employ (name,Snumber,Gnumber,Salary) '
SET #sql += N'SELECT ' + QUOTENAME(#name, '''')
SET #sql += N', ' + CAST(#snum AS NVARCHAR(50))
SET #sql += N', ' + CAST(#gnum AS NVARCHAR(50))
SET #sql += N', s' + CAST(#snum AS NVARCHAR(50))
SET #sql += N' FROM dbo.GrideBtable'
SET #sql += N' WHERE Gnumber = ' + QUOTENAME(#g, '''')
EXEC (#sql)
Of course you could add the #g variable to the procedure parameters instead of having it hard coded in the procedure and call it as:
EXEC insertperoll #name='john', #snum=10, #gnum=100, #g='g1'
Sample SQL Fiddle (with some assumptions made about table structure)
You could do this using sp_executesql instead of exec() since this will allow you to use parameters, you can use an output parameter to get the value from the query:
DECLARE #SQL NVARCHAR(MAX) = N'SELECT #val = ' + CONVERT(NVARCHAR(10),#snum) +
N' FROM dbo.GrideBtable WHERE Gnumber = #G1';
DECLARE #val INT; -- NOT SURE OF DATATYPE REQUIRED
EXECUTE sp_executesql #SQL, N'#G1 VARCHAR(20), #val INT OUT', 'G1', #val OUT;