Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

como dividir e inserir dados CSV em uma nova tabela em uma única instrução?


Você precisa de uma maneira de dividir e processar a string em TSQL, existem muitas maneiras de fazer isso. Este artigo aborda os prós e contras de praticamente todos os métodos:

Arrays e listas no SQL Server 2005 e posterior

Você precisa criar uma função de divisão. É assim que uma função de divisão pode ser usada:
SELECT
    *
    FROM YourTable                               y
    INNER JOIN dbo.yourSplitFunction(@Parameter) s ON y.ID=s.Value

Prefiro a abordagem de tabela numérica para dividir uma string em TSQL - usando um Tabela de Números mas existem várias maneiras de dividir strings no SQL Server, veja o link anterior, que explica os prós e contras de cada um.

Para que o método Numbers Table funcione, você precisa fazer esta configuração de tabela de tempo, que criará uma tabela Numbers que contém linhas de 1 a 10.000:
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO Numbers
    FROM sys.objects s1
    CROSS JOIN sys.objects s2
ALTER TABLE Numbers ADD CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number)

Depois que a tabela Numbers estiver configurada, crie esta função de divisão:
CREATE FUNCTION inline_split_me (@SplitOn char(1),@param varchar(7998)) RETURNS TABLE AS
   RETURN(SELECT substring(@SplitOn + @param + ',', Number + 1,
                    charindex(@SplitOn, @SplitOn + @param + @SplitOn, Number + 1) - Number - 1)
                 AS Value
          FROM   Numbers
          WHERE  Number <= len(@SplitOn + @param + @SplitOn) - 1
            AND  substring(@SplitOn + @param + @SplitOn, Number, 1) = @SplitOn)

GO 

Agora você pode facilmente dividir uma string CSV em uma tabela e juntá-la:
select * from dbo.inline_split_me(';','1;22;333;4444;;') where LEN(Value)>0

RESULTADO:
Value
----------------------
1
22
333
4444

(4 row(s) affected)

para fazer sua nova tabela, use isso:
--set up tables:
DECLARE @Documents table (DocumentID varchar(500), SomeValue varchar(5))
INSERT @Documents VALUES ('1,2,3,4','AAA')
INSERT @Documents VALUES ('5,6'    ,'BBBB')

DECLARE @NewDocuments table (DocumentID int, SomeValue varchar(5))

--populate NewDocuments
INSERT @NewDocuments
    (DocumentID, SomeValue)
SELECT
    c.value,a.SomeValue
    FROM @Documents    a
        CROSS APPLY dbo.inline_split_me(',',a.DocumentID) c

 --show NewDocuments contents:
select * from @NewDocuments

RESULTADO:
DocumentID  SomeValue
----------- ---------
1           AAA
2           AAA
3           AAA
4           AAA
5           BBBB
6           BBBB

(6 row(s) affected)

se você não quiser criar uma tabela Numbers e estiver executando o SQL Server 2005 ou superior, basta usar esta função de divisão (não é necessária nenhuma tabela Numbers):
CREATE FUNCTION inline_split_me (@SplitOn char(1),@String varchar(7998))
RETURNS TABLE AS
RETURN (WITH SplitSting AS
           (SELECT
                LEFT(@String,CHARINDEX(@SplitOn,@String)-1) AS Part
                    ,RIGHT(@String,LEN(@String)-CHARINDEX(@SplitOn,@String)) AS Remainder
                WHERE @String IS NOT NULL AND CHARINDEX(@SplitOn,@String)>0
            UNION ALL
            SELECT
                LEFT(Remainder,CHARINDEX(@SplitOn,Remainder)-1)
                    ,RIGHT(Remainder,LEN(Remainder)-CHARINDEX(@SplitOn,Remainder))
                FROM SplitSting
                WHERE Remainder IS NOT NULL AND CHARINDEX(@SplitOn,Remainder)>0
            UNION ALL
            SELECT
                Remainder,null
                FROM SplitSting
                WHERE Remainder IS NOT NULL AND CHARINDEX(@SplitOn,Remainder)=0
           )
           SELECT Part FROM SplitSting
       )
GO