I need to use a comma delimited string for SQL AND condition on each word

▼魔方 西西 提交于 2019-12-01 21:35:43

One relational division approach using the ProductTags table is

DECLARE @TagsToSearch TABLE (
  TagId VARCHAR(50) PRIMARY KEY )

INSERT INTO @TagsToSearch
VALUES      ('Red'),
            ('Large'),
            ('New')

SELECT PT.ProductID
FROM   ProductTags PT
       JOIN @TagsToSearch TS
         ON TS.TagId = PT.TagId
GROUP  BY PT.ProductID
HAVING COUNT(*) = (SELECT COUNT(*)
                   FROM   @TagsToSearch) 

The @TagsToSearch table would ideally be a table valued parameter passed directly from your application but could also be populated by using a split function against your comma delimited parameter.

You just need to add wildcards:

SELECT * 
FROM MyTable 
WHERE    ','+Tags+',' LIKE '%,FirstWordInString,%'
     AND ','+Tags+','Like '%,SecondWordInString,%'
     AND ','+Tags+','Like '%,ThirdWordInString,%'

UPDATE: I understand now the problem is that you have a variable you are trying to match the tags to. The variable has the string list of tags. If you split the list of user selected tags using a split string function, or can get the user selected tags from input form separately, then you can just use:

SELECT *
FROM MyTable
WHERE ',,'+Tags+',' LIKE '%,'+@tag1+',%'
         AND ',,'+Tags+',' LIKE '%,'+@tag2+',%'
         AND ',,'+Tags+',' LIKE '%,'+@tag3+',%'
         AND ',,'+Tags+',' LIKE '%,'+@tag4+',%'

etc.

This will work for any number of entered tags, as an empty @tag would result in the double comma appended to the tags field matching '%,,%'.

From codeproject:

-- =============================================
-- Author: Md. Marufuzzaman
-- Create date: 
-- Description: Split an expression. 
-- Note: If you are using SQL Server 2000, You need to change the 
-- length (MAX) to your maximum expression length of each datatype.
-- =============================================
/*
SELECT * FROM [dbo].[SPLIT] (';','I love codeProject;!!!;Your development resources')
*/
CREATE FUNCTION [dbo].[SPLIT] 
(  @DELIMITER VARCHAR(5), 
  @LIST      VARCHAR(MAX) 
 ) 
   RETURNS @TABLEOFVALUES TABLE 
  (  ROWID   SMALLINT IDENTITY(1,1), 
     [VALUE] VARCHAR(MAX) 
  ) 
AS 
BEGIN

  DECLARE @LENSTRING INT 

  WHILE LEN( @LIST ) > 0 
     BEGIN 

        SELECT @LENSTRING = 
           (CASE CHARINDEX( @DELIMITER, @LIST ) 
               WHEN 0 THEN LEN( @LIST ) 
               ELSE ( CHARINDEX( @DELIMITER, @LIST ) -1 )
            END
           ) 

        INSERT INTO @TABLEOFVALUES 
           SELECT SUBSTRING( @LIST, 1, @LENSTRING )

        SELECT @LIST = 
           (CASE ( LEN( @LIST ) - @LENSTRING ) 
               WHEN 0 THEN '' 
               ELSE RIGHT( @LIST, LEN( @LIST ) - @LENSTRING - 1 ) 
            END
           ) 
     END

  RETURN 

END

http://www.codeproject.com/Articles/38843/An-Easy-But-Effective-Way-to-Split-a-String-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!