Split sql parameter on comma

前端 未结 4 771
春和景丽
春和景丽 2021-01-14 20:04

Below code works for \'Main Stream\' or \'Premium\' as parameter, however I am trying to make it work for both of them as you can see below, but it doesn\'t return any resul

4条回答
  •  时光说笑
    2021-01-14 20:46

    I found a nice solution for a similar issue on another thread on SO.
    Basically, it uses a function for splitting a string (@MyParameter in your case) using a delimiter (',' in your case).

    Here is how you call the function:

    declare @myParameter varchar(50)
    SET @myParameter = 'Main Stream,Premium'
    
    --this table will hold delimited values
    DECLARE @ParsedTable TABLE 
    (   
            [id] [int] NOT NULL,
            [content] [nvarchar](50) NULL
    )
        --Parsing @myParameter
    INSERT INTO @ParsedTable
    SELECT * from [dbo].[SplitString](@myParameter, ',')
    --SELECT * FROM @ParsedTable --This will show you the values... 
    --run the query 
    select * FROM sales  
    where myCategory IN (SELECT content from @ParsedTable)
    

    And here is the code for creating the split functions:

    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SplitString]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
    DROP FUNCTION [dbo].[SplitString]
    go
    
    /****** Object:  UserDefinedFunction [dbo].[SplitString]    Script Date: 11/04/2013 19:04:05 ******/
    SET ANSI_NULLS ON
    go
    
    SET QUOTED_IDENTIFIER ON
    go
    
    CREATE FUNCTION [dbo].[SplitString] 
    (
        -- Add the parameters for the function here
        @StringToDelimit nvarchar(500),
        @deliminator nvarchar(2)
    )
    RETURNS 
    @ReturnTable TABLE 
    (
        -- Add the column definitions for the TABLE variable here
        [id] [int] IDENTITY(1,1) NOT NULL,
        [content] [nvarchar](50) NULL
    )
    AS
    BEGIN
            Declare @delimitorIdx int
            Declare @content varchar(50)
    
            --initialize spaces
            Select @delimitorIdx = charindex(@deliminator,@StringToDelimit,0)
            While @delimitorIdx > 0
    
            Begin
                Select @content = substring(@StringToDelimit,0,charindex(@deliminator,@StringToDelimit,0))
    
                Insert Into @ReturnTable(content)
                Select @content
    
                Select @StringToDelimit = substring(@StringToDelimit,charindex(@deliminator,@StringToDelimit,0)+ 1,len(@StringToDelimit) - charindex(' ',@StringToDelimit,0))
    
                Select @delimitorIdx = charindex(@deliminator,@StringToDelimit,0)
            end
    
            If len(@StringToDelimit) > 0
                Insert Into @ReturnTable
                Select @StringToDelimit
    
        RETURN 
    END
    
    go
    

提交回复
热议问题