Passing comma-separated value from .NET to stored procedure using the value in “IN” SQL function

前端 未结 3 1899
粉色の甜心
粉色の甜心 2021-01-13 04:12

I have an SQL query similar to the following:

create procedure test
(
   @param1 nvarchar(max)
)
as
begin
    select * from table where column1 in (@param1)
         


        
3条回答
  •  野的像风
    2021-01-13 04:39

    For this type of thing, I use this function and use it as follows:

    select Column1, column2 from my table where ID in (select item from fnSplit('1,2,3,4,5,6',','))

    create FUNCTION [dbo].[fnSplit](
            @sInputList VARCHAR(8000) -- List of delimited items
          , @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
        ) 
    
    RETURNS @List TABLE (item VARCHAR(8000))
    
    BEGIN
    DECLARE @sItem VARCHAR(8000)
    WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
     BEGIN
     SELECT
      @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
      @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
    
     IF LEN(@sItem) > 0
      INSERT INTO @List SELECT @sItem
     END
    
    IF LEN(@sInputList) > 0
     INSERT INTO @List SELECT @sInputList -- Put the last item in
    RETURN
    END
    

提交回复
热议问题