How to create a SQL function which splits comma separated value?

我与影子孤独终老i 提交于 2021-02-11 16:27:32

问题


I want to create a function in SQL Server which takes a comma separated string a parameter, splits it and returns one value at a time. The basic idea here is to call that function from a query. Something like this.

CREATE FUNCTION SPLIT_VALUE(@IN_CSV)
RETURN VARCHAR AS
 -- LOGIC TO RETURN A SINGLE VALUE FROM CSV
END

I want to call this function from a stored procedure.

CREATE PROCEDURE DEMO_PROC @IN_CSV VARCHAR(5000), @OUT VARCHAR(5000) OUTPUT AS
   BEGIN
     SELECT @OUT= CONCAT(A.VALUE1,B.VALUE2) FROM TABLE1 A INNER JOIN TABLE2 B ON A.ID=B.ID WHERE A.ID 
     IN(--CALL THE FUNCTION AND GET ONE VALUE);
   END;

I have to create a loop or cursor to point to a particular value every time. Is this practically possible to? If yes then how can I do that?


回答1:


Like I mention, you'll have to use a CURSOR to do this, however, the fact you want to do it this way infers a (large) design flaw:

DECLARE @value varchar(8000)

DECLARE Delimited_Values CURSOR FAST_FORWARD
FOR
SELECT [value]
FROM STRING_SPLIT('a,b,c,d,e',',')

OPEN Delimited_Values;

FETCH NEXT FROM Delimited_Values
INTO @value;

WHILE @@FETCH_STATUS = 0 BEGIN

    SELECT @value; --Do your stuff here

    FETCH NEXT FROM Delimited_Values
    INTO @value;

END;

CLOSE Delimited_Values;
DEALLOCATE Delimited_Values;


来源:https://stackoverflow.com/questions/62536647/how-to-create-a-sql-function-which-splits-comma-separated-value

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