Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come dividere la stringa in colonne per una vista?

Ecco un modo semplice e veloce:

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

Risultati:

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

E ecco un sqlfiddle con una demo.