SQL Server Hosting – HostForLIFE.eu :: How to Convert String To Table List in MS-SQL?
|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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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 END |
Output
We can send the list as a string, as it converts against as a list of rows.
SELECT Result FROM DBO.UF_StrToTable(‘1,2,3,4,5′,’,’)
Run the query given above in SQL Server and here is the output: