DECLARE @TagSearch AS TABLE
(
[TYPE] NVARCHAR(50)
,[ID] Bigint
, [Tags] NVARCHAR(50)
)
INSERT INTO @TagSearch
SELECT 'typ1',1,'tag3,a,b,c'
Union all
SELECT 'type3',2,'tag4,r,e'
Union all
SELECT 'asf',3,'tag5,y,u,q,e,w'
Union all
SELECT 'aaa',4,'e,f,g,h'
DECLARE @Tags AS NVARCHAR(255)
SELECT @Tags=REPLACE('tag3 r u',' ',',')
Create one table level function for below code and mention @Tags as parameter name
Step by step explanation of code
1) Create one variable to store each tags (in this case our tags are tag3 , r and u)
2) Create one variable to store position to separate each tag from string(in this case our string is 'tag3 r u')
3) Loop through the string and extract each tag after comma and then search that tag in table(here we are using "@TagSearch" but you can mention your table name)
DECLARE @Tag nvarchar(255), @Pos int
SET @Tags = LTRIM(RTRIM(@Tags))+ ','
SET @Pos = CHARINDEX(',', @Tags, 1)
IF REPLACE(@Tags, ',', '') <> ''
BEGIN
WHILE @Pos > 0
BEGIN
SET @Tag = LTRIM(RTRIM(LEFT(@Tags, @Pos - 1)))
IF @Tag <> ''
BEGIN
SELECT * FROM @TagSearch WHERE [Tags] Like '%' + @Tag + '%'
END
SET @Tags = RIGHT(@Tags, LEN(@Tags) - @Pos)
SET @Pos = CHARINDEX(',', @Tags, 1)
END
END