I have \'param1, param2, parma3\'
coming from SSRS to a stored procedure as a varchar
parameter: I need to use it in a query\'s IN
cla
"Best way" is arguable, but one classic approach that remains without "creating functions and table parameters" is to simply employ dynamic SQL in the stored procedure:
-- FORNOW: local to act as the SP param and arg
declare @values varchar(100) = 'param1, param2, param3'
-- Add opening and closing single quotes, then quotes around each
-- comma-separated list item.
select @values = '''' + REPLACE(@values, ', ', ''', ''') + ''''
-- FORNOW: for clarity/debugging
print @values
--'param1', 'param2', 'param3'
-- Run the desired query as dynamic SQL.
DECLARE @sql as nvarchar(250);
SET @sql = 'select * from table1 where col1 in (' + @values + ')';
EXEC sp_executesql @sql;
This assumes a couple things, though:
If you are using SQL 2016 and above string_split
you can use.
-- @param is where you keep your comma separated values example:
declare @param = 'param1,param2,param3'
select * from table1 where col1 in (select TRIM(value) from string_split(@param,',')
More information about string_split check offical documemt
Furthermore, TRIM()
is used to trim values from white spaces.
Load the Params into a string and execute as an sql :
declare @param varchar(1000) = 'param1, param2, parma3'
declare @sql varchar(4000)
select @sql =
'select *
from table1
where col1 in(''' + replace(@param,',',''',''') + ''')'
-- print @sql -- to see what you're going to execute
exec sp_executesql @sql
Try this one, Just need to add commas at the beginning and at the end of @params string.
Declare @params varchar(100) Set @params = ',param1,param2,param3,'
Select * from t
where CHARINDEX(','+cast(col1 as varchar(8000))+',', @params) > 0
SQL FIDDLE
you can use split function and use it as in following way here my split fnSplitString return splitdata
select * from tb1 where id in(select splitdata from dbo.fnSplitString((select col1 from tb12 where id=3),','))
create FUNCTION [dbo].[fnSplitString]
(
@string NVARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS @output TABLE(splitdata NVARCHAR(MAX)
)
BEGIN
DECLARE @start INT, @end INT
SELECT @start = 1, @end = CHARINDEX(@delimiter, @string)
WHILE @start < LEN(@string) + 1 BEGIN
IF @end = 0
SET @end = LEN(@string) + 1
INSERT INTO @output(splitdata)
VALUES(SUBSTRING(@string, @start, @end - @start))
SET @start = @end + 1
SET @end = CHARINDEX(@delimiter, @string, @start)
END
RETURN
END