Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

Comment diviser une chaîne en colonnes pour une vue ?

Voici un moyen simple et rapide :

DECLARE @T TABLE(full_location_id varchar(100));

INSERT INTO @T 
VALUES  ('A1-BF-35-B1'),
        ('AR-B3');

WITH CTE AS
(
    SELECT  full_location_id,
            LEN(full_location_id)-LEN(REPLACE(full_location_id,'-','')) N
    FROM @T
)
SELECT  full_location_id,
        PARSENAME(REPLACE(full_location_id,'-','.'),N+1),
        PARSENAME(REPLACE(full_location_id,'-','.'),N),
        PARSENAME(REPLACE(full_location_id,'-','.'),N-1),
        PARSENAME(REPLACE(full_location_id,'-','.'),N-2)
FROM CTE

Résultats :

╔══════════════════╦══════╦══════╦══════╦══════╗
║ full_location_id ║ Col1 ║ Col2 ║ Col3 ║ Col4 ║
╠══════════════════╬══════╬══════╬══════╬══════╣
║ A1-BF-35-B1      ║ A1   ║ BF   ║ 35   ║ B1   ║
║ AR-B3            ║ AR   ║ B3   ║ NULL ║ NULL ║
╚══════════════════╩══════╩══════╩══════╩══════╝

Et voici un sqlfiddle avec une démo.