sql server - Passing a variable into an IN clause within a SQL function? -
possible duplicate:
parameterizing sql in clause?
i have sql function whereby need pass list of ids in, string, into:
where id in (@mylist)
i have looked around , of answers either sql built within c# , loop through , call addparameter, or sql built dynamically.
my sql function large , building query dynamically rather tedious.
is there no way pass in string of comma-separated values in clause?
my variable being passed in representing list of integers be:
"1,2,3,4,5,6,7" etc
passing string directly in clause not possible. however, if providing list string stored procedure, example, can use following dirty method.
first, create function:
create function [dbo].[fnntexttointtable] (@data ntext) returns @inttable table ([value] int null) begin declare @ptr int, @length int, @v nchar, @vv nvarchar(10) select @length = (datalength(@data) / 2) + 1, @ptr = 1 while (@ptr < @length) begin set @v = substring(@data, @ptr, 1) if @v = ',' begin insert @inttable (value) values (cast(@vv int)) set @vv = null end else begin set @vv = isnull(@vv, '') + @v end set @ptr = @ptr + 1 end -- if last number not followed comma, add result set if @vv not null insert @inttable (value) values (cast(@vv int)) return end (note: not original code, versioning systems here @ place of work, have lost header comment linking source.)
then use so:
select * tblmytable inner join fnntexttointtable(@mylist) list on tblmytable.id = list.value or, in question:
select * tblmytable id in ( select value fnntexttointtable(@mylist) )
Comments
Post a Comment