If the widths of the fields are always fixed as well, i.e., 1 character (Y/N), then it's as simple as using the substring
function to get all the individual field values:
;with Data as (
select 'Y|N|Y|Y' as choices union
select 'Y|Y|Y|Y' as choices union
select 'Y|N|N|Y' as choices union
select 'Y|N|N|N' as choices union
select 'N|N|Y|N' as choices union
select 'Y|Y|N|Y' as choices
)
select
substring(choices, 1, 1) as field1,
substring(choices, 3, 1) as field2,
substring(choices, 5, 1) as field3,
substring(choices, 7, 1) as field4
from
Data
Output:
field1 field2 field3 field4
N N Y N
Y N N N
Y N N Y
Y N Y Y
Y Y N Y
Y Y Y Y
If you can't guarantee that the widths of the fields are the same, you can make use of charindex
and a helper table of field indexes to generate the output you are looking for. This becomes very verbose as the number of fields grows larger, but you should only have to write it once if the number of fields is going to be fixed:
;with Data as (
select 1 as id, 'Y|N|Y|Y' as choices union
select 2,'Y|Y|Y|Y' as choices union
select 3,'Y|No|N|Y' as choices union
select 4,'Yes|N|N|N' as choices union
select 5,'N|N|Yes|No' as choices union
select 6,'Y|Y|N|Yes' as choices
), Fields as (
select
id,
charindex('|', choices) as field1end,
charindex('|', choices, charindex('|', choices) + 1) as field2end,
charindex('|', choices, charindex('|', choices, charindex('|', choices) + 1) + 1) as field3end,
len(choices) + 1 as field4end
from
Data
)
select
substring(choices, 1, field1end - 1) as field1,
substring(choices, field1end + 1, field2end - field1end - 1) as field2,
substring(choices, field2end + 1, field3end - field2end - 1) as field3,
substring(choices, field3end + 1, field4end - field3end - 1) as field4
from
Data D
inner join
Fields F on D.id = F.id
Output:
field1 field2 field3 field4
Y N Y Y
Y Y Y Y
Y No N Y
Yes N N N
N N Yes No
Y Y N Yes