Använd splitterfunktionen nedan som returnerar en int-kolumn. Så det är lätt att kontrollera antalet i HAVING-satsen.
CREATE FUNCTION [dbo].[DelimitedParamParser]( @DelimitedIds VARCHAR(MAX), @Delimiter CHAR(1))
RETURNS @IdsTable
TABLE ( Id INT )
AS BEGIN
DECLARE @Length INT,
@Index INT,
@NextIndex INT
SET @Length = DATALENGTH(@DelimitedIds)
SET @Index = 0
SET @NextIndex = 0
WHILE (@Length > @Index )
BEGIN
SET @NextIndex = CHARINDEX(@Delimiter, @DelimitedIds, @Index)
IF (@NextIndex = 0 ) SET @NextIndex = @Length + 2
INSERT @IdsTable SELECT SUBSTRING( @DelimitedIds, @Index, @NextIndex - @Index )
SET @index = @nextindex + 1
END
RETURN
END
Detta fungerar, tänk på att ge ett extra kommatecken i slutet.
DECLARE @DELIMITER CHAR = ','
DECLARE @CSV_STRING VARCHAR(20) = '1,3,'
SELECT Distinct SUPER_HERO.NAME, SKILL.NAME
FROM
SUPER_HERO
INNER JOIN SUPER_HERO_SKILL ON SUPER_HERO_SKILL.SUPER_HERO_ID = SUPER_HERO.ID
INNER JOIN SKILL ON SUPER_HERO_SKILL.SKILL_ID = SKILL.ID
WHERE SUPER_HERO.ID IN
(
SELECT SUPER_HERO_SKILL.SUPER_HERO_ID
FROM
SUPER_HERO
INNER JOIN SUPER_HERO_SKILL ON SUPER_HERO_SKILL.SUPER_HERO_ID = SUPER_HERO.ID
INNER JOIN SKILL ON SUPER_HERO_SKILL.SKILL_ID = SKILL.ID
INNER JOIN DelimitedParamParser(@CSV_STRING, @DELIMITER) SPLIT ON SPLIT.ID = SUPER_HERO_SKILL.SKILL_ID
GROUP BY SUPER_HERO_SKILL.SUPER_HERO_ID
HAVING COUNT(DISTINCT(SUPER_HERO_SKILL.SKILL_ID)) = (SELECT COUNT(DISTINCT(Id)) FROM DelimitedParamParser(@CSV_STRING, @DELIMITER))
)