Create a function
When we start programming in any language, mostly we use loop and we hit Server side code to list the data every time. This function is helpful in reducing our Server side code & increase Application performance.
SQL
CREATE FUNCTION[dbo].[UF_StrToTable](@String VARCHAR(MAX), @Delimiter CHAR(1))
RETURNS @Temptable TABLE(Result VARCHAR(8000))
AS
BEGIN
DECLARE @INDEX int, @SLICE VARCHAR(8000)
SELECT @INDEX = 1
IF LEN(@String) < 1 OR @String IS NULL
return
WHILE @INDEX != 0
BEGIN
SET @INDEX = CHARINDEX(@Delimiter, @String)
IF @INDEX != 0
BEGIN
SET @SLICE = LEFT(@String, @INDEX - 1)
END
ELSE
BEGIN
SET @SLICE = @String
END
IF(LEN(@SLICE) > 0)
BEGIN
INSERT INTO @Temptable(Result) VALUES(@SLICE)
END
SET @String = RIGHT(@String, LEN(@String) - @INDEX)
IF LEN(@String) = 0
break
END
RETURN
ENDOutput
We can send the list as a string, as it converts against as a list of rows.
SQL
SELECT Result FROM DBO.UF_StrToTable('1,2,3,4,5',',')Run the query given above in SQL Server & see the result.



Manav PandyaPosted Apr 18, 2017, 5:58 AM EDT
Nicce ............
Former memberPosted Mar 29, 2017, 1:19 AM EDT
This line is not clear RETURNS @Temptable TABLE(Result VARCHAR(8000)) where is the definition of @Temptable ? what is TABLE(Result VARCHAR(8000)) ? which minimum version of sql server require to run your code. good link from where i understand multi line table value function https://www.codeproject.com/Articles/1115166/Creating-and-using-Table-valued-function-in-SQL-Se
Anu VPosted Mar 28, 2017, 3:37 AM EDT
Thanks for sharing.. nice article..