Como crear una funcion para separar por filas o columnas mediante un separador: Funcion Split por columna y fila
Split por columna y fila (Column and Row)
Primero aclaremos que un split(o dividir) es una matriz unidimensional, sea por filas o columnas normalmente utilizamos split para obtener filas, pero en este articulo usaremos ambos métodos
Importante mencionar que para SQL 2016 la función split ya viene en modo nativo, pueden validar el siguiente link https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql
La función STRING_SPLIT solo está disponible en el nivel de compatibilidad 130. Si el nivel de compatibilidad de su base de datos es inferior a 130, SQL Server no podrá encontrar y ejecutar la función STRING_SPLIT . Puede cambiar un nivel de compatibilidad de la base de datos con el siguiente comando:
ALTER DATABASE DatabaseName SET COMPATIBILITY_LEVEL = 130
Tenga en cuenta que el nivel de compatibilidad 120 puede ser el predeterminado incluso en las nuevas bases de datos SQL de Azure.
Pero como seguramente aun no tenemos SQL Server 2016 nos toca crear nuestras propias funciones split, para lo cual pueden segir el articulo
para el ejemplo leeremos un archivo plano, y el delimitador sera la coma («,») ,pero debemos separarlo tanto por filas como columnas ?, para lo cual crearemos una función para cada caso;
Función separar por columnas
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 |
USE [MaktubSQL] go SET ansi_nulls ON go SET quoted_identifier ON go CREATE FUNCTION [dbo].[Funcion_separar_por_columnas](@TEXT VARCHAR(8000), @COLUMN TINYINT, @SEPARATOR CHAR(1)) returns VARCHAR(8000) AS BEGIN DECLARE @POS_START INT = 1 DECLARE @POS_END INT = Charindex(@SEPARATOR, @TEXT, @POS_START) WHILE ( @COLUMN > 1 AND @POS_END > 0 ) BEGIN SET @POS_START = @POS_END + 1 SET @POS_END = Charindex(@SEPARATOR, @TEXT, @POS_START) SET @COLUMN = @COLUMN - 1 END IF @COLUMN > 1 SET @POS_START = Len(@TEXT) + 1 IF @POS_END = 0 SET @POS_END = Len(@TEXT) + 1 RETURN Substring (@TEXT, @POS_START, @POS_END - @POS_START) END GO |
Ejecutar nuestra función
1 2 3 4 5 6 7 8 |
SELECT [dbo].[Funcion_separar_por_columnas]('Juan,Andreina,Sevastian,Viviana,Pepito', 1 , ',') AS Columna1SELECT [dbo].[Funcion_separar_por_columnas]('Juan,Andreina,Sevastian,Viviana,Pepito', 5 , ',') AS Columna5 |
Función separar por filas
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
SET ansi_nulls ON go SET quoted_identifier ON go CREATE FUNCTION [dbo].[Ufn_split] (@string NVARCHAR(max), @delimiter CHAR(1)) returns @output TABLE( splitdata NVARCHAR(max)) BEGIN DECLARE @start INT, @end INT SELECT @start = 1, @end = Charindex(@delimiter, @string) WHILE @start < Len(@string) + 1 BEGIN IF @end = 0 SET @end = Len(@string) + 1 INSERT INTO @output (splitdata) VALUES (Substring(@string, @start, @end - @start)) SET @start = @end + 1 SET @end = Charindex(@delimiter, @string, @start) END RETURN END GO |
1 2 3 4 5 |
SELECT * FROM [dbo].[Ufn_split] ('Juan,Andreina,Sevastian,Viviana,Pepito', ',') GO |