Sqlserver
 sql >> база данни >  >> RDS >> Sqlserver

Как мога да разделя стойността на колоната на различни колони в SQL

declare @T table
(
  col_1 varchar(100)
)

insert into @T values
('aa,ab,ac,4,5,6,7,8,9,10'),
('ba,bb,bc,4,5,6,7,8,9,10'),
('ca,cb,cc,4,5,6,7,8,9,10')

select left(T.col_1, C1.Pos-1) as col_1,
       substring(T.col_1, C1.Pos+1, C2.Pos-C1.Pos-1)  as col_2,
       substring(T.col_1, C2.Pos+1, C3.Pos-C2.Pos-1)  as col_3,
       substring(T.col_1, C3.Pos+1, C4.Pos-C3.Pos-1)  as col_4,
       substring(T.col_1, C4.Pos+1, C5.Pos-C4.Pos-1)  as col_5,
       substring(T.col_1, C5.Pos+1, C6.Pos-C5.Pos-1)  as col_6,
       substring(T.col_1, C6.Pos+1, C7.Pos-C6.Pos-1)  as col_7,
       substring(T.col_1, C7.Pos+1, C8.Pos-C7.Pos-1)  as col_8,
       substring(T.col_1, C8.Pos+1, C9.Pos-C8.Pos-1)  as col_9,
       stuff(T.col_1, 1, C9.Pos, '') as col_10
from @T as T
  cross apply (select charindex(',', col_1)) as C1(Pos)
  cross apply (select charindex(',', col_1, C1.Pos+1)) as C2(Pos)
  cross apply (select charindex(',', col_1, C2.Pos+1)) as C3(Pos)
  cross apply (select charindex(',', col_1, C3.Pos+1)) as C4(Pos)
  cross apply (select charindex(',', col_1, C4.Pos+1)) as C5(Pos)
  cross apply (select charindex(',', col_1, C5.Pos+1)) as C6(Pos)
  cross apply (select charindex(',', col_1, C6.Pos+1)) as C7(Pos)
  cross apply (select charindex(',', col_1, C7.Pos+1)) as C8(Pos)
  cross apply (select charindex(',', col_1, C8.Pos+1)) as C9(Pos)


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. PHP MsSQL PDO или API

  2. Изберете уникални имена на колони от списък с обединени таблици

  3. Сравнете изтритата и вмъкната таблица в SQL Server 2008

  4. Изпълнение на външно приложение с функция

  5. Изберете в израз, където източникът е друга база данни