Hello I need to make a sql request that takes multi parameters in a 'WHERE (abc IN @par1, @par2 ....' To do so, I found some solutions that use a sql function. I tried to use it without any success. I'm working on workbench and this is my function code.
CREATE function MultiStringToTable (InStr VARCHAR(255))
RETURNS @TempTab TABLE(
id nvarchar(255) not null
)
AS
BEGIN
-- Ensure input ends with comma
SET @InStr = REPLACE(@InStr + ',', ',,', ',');
DECLARE @SP INT;
DECLARE @VALEUR VARCHAR(1000);
WHILE PATINDEX('%,%', @INSTR ) <> 0
SET @SP = PATINDEX('%,%',@INSTR);
SET @VALEUR = LEFT(@INSTR , @SP - 1);
SET @INSTR = STUFF(@INSTR, 1, @SP, '');
INSERT INTO @TempTab(id) VALUES (@VALEUR);
END;
RETURN;
end;
It causes problem on the '@TempTab'.
Thanks for help.
First - Artem beat me to it but the correct code is:
That said - ^^^ This is going to be horribly slow. For what you are doing you can use STRING_SPLIT.
Done. Better yet, you can have any number of commas and they will be treated as one. Note the change below:
This returns:
To understand the performance difference let's do a quick test.
STRING_SPLIT is about One Hundred times faster and with much less code to boot.