Вы можете справиться с этим, используя несколько CTE, разделенных запятыми.
Ниже в запросе есть две таблицы CTE t0
и t1
.Таблица t0 определяет положение первого ']'
, используя функцию charindex
, и аналогично, t1
используется для определения положения следующего ']'
.
Используя функцию case statement
и substring
, вы можете получить желаемый результат.
with t0 as ( select Column1, Column2 , Column3, charindex(']',Column1) pos from #tbl),
t1 as (select Column1, Column2 , Column3, charindex(']',Column1,t0.pos+1) pos from t0)
select case when t0.pos = 0 then t0.column1 else substring(t0.Column1,0, t0.pos ) end Column1,
case when t0.pos = 0 then null else substring(t0.Column1,t0.pos+1,case when t1.pos= 0 then len(t0.Column1)+1 else len(t0.Column1)- t1.pos end)end Column2,
case when (t0.pos = 0 or(t0.pos <>0 and t1.pos =0)) then null else substring(t0.Column1,t1.pos+1, len(t0.Column1)+1 ) end Column3
from t0
inner join t1 on t0.Column1 = t1.Column1
выход
Column1 Column2 Column3
------- ------- -------
A NULL NULL
A B NULL
A B C