Felipe, your request contains two of the most frequently asked questions on SQL forums: (1) break a character string containing several fields separated by a delimiter (split string) and (2) turn "one row / multiple columns" into "multiple rows / one column" (unpivot).
About the first part, split string, there are several interesting articles on the subject, in which you will find various solutions to the problem. I suggest reading article "Separating multi-valued text content (split string)”.
On the second part, unpivot, here are articles on the subject:
For demonstration was used the Splitstrings_moden function, which is derived from a function created by Jeff Moden. It performs the split string and also the unpivot.
Code #1 generates a temporary table (table variable) to simulate the data. The call of the split string was made in the FROM clause (using cross apply), as it is a function of the type table-Valued.
-- código #1
declare @Retorno table (ID int identity, Resultado varchar(max));
INSERT into @Retorno (Resultado) values
('0000000.0000001.0000002.0000003.0000004.0000005.0000006'),
(replicate('8888888.',400) + '0000000'),
('0123456');
SELECT T.ID, U.Item
from @Retorno as T
cross apply dbo.splitStrings_Moden(T.Resultado,'.') as U;
Below, the code transcription of the Splitstrings_moden function.
-- código #2
CREATE FUNCTION dbo.SplitStrings_Moden
(
@List NVARCHAR(MAX),
@Delimiter NVARCHAR(255)
)
RETURNS TABLEfaz
WITH SCHEMABINDING AS
RETURN
WITH E1(N) AS ( SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1),
E2(N) AS (SELECT 1 FROM E1 a, E1 b),
E4(N) AS (SELECT 1 FROM E2 a, E2 b),
E42(N) AS (SELECT 1 FROM E4 a, E2 b),
cteTally(N) AS (SELECT 0 UNION ALL SELECT TOP (DATALENGTH(ISNULL(@List,1)))
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E42),
cteStart(N1) AS (SELECT t.N+1 FROM cteTally t
WHERE (SUBSTRING(@List,t.N,1) = @Delimiter OR t.N = 0))
SELECT Item = SUBSTRING(@List, s.N1, ISNULL(NULLIF(CHARINDEX(@Delimiter,@List,s.N1),0)-s.N1,8000))
FROM cteStart s;
go
http://stackoverflow.com/questions/15477743/listagg-in-sqlserver
– Motta
You said "SQL function", this is done by the function or the data is stored this way in the table?
– Marco Souza
@Felipenegro Complementing Marconcílio’s question, the original function is of the scalar or table-Valued type?
– José Diz
@Marconciliosouza In my BD I have a function (Function) that returns a single column and row. The result is a string/varchar of dot-separated numbers (Example: 123,456,789,012 etc.) and has no specific size. On this link I was able to get the result I needed http://zavaschi.com/index.php/2009/06/repostagem-funo-split-no-sql-server/
– Felipe Negro
@Josédiz is the Escalar type
– Felipe Negro