If the
PartDone
is always four numbers, then you don't need a
PIVOT
:
DECLARE @tmp TABLE (partId int, PartDone char(4));
INSERT INTO @tmp (partId, partDone)
VALUES
(555444, '0012'),
(911877, '0221')
;
SELECT
partId,
PartDone,
CASE Substring(PartDone, 1, 1)
WHEN '0' THEN 'no'
WHEN '1' THEN 'yes'
END As [first],
CASE Substring(PartDone, 2, 1)
WHEN '0' THEN 'no'
WHEN '1' THEN 'yes'
END As [second],
CASE Substring(PartDone, 3, 1)
WHEN '0' THEN 'no'
WHEN '1' THEN 'yes'
END As [third],
CASE Substring(PartDone, 4, 1)
WHEN '0' THEN 'no'
WHEN '1' THEN 'yes'
END As [fourth]
FROM
@tmp
;
NB: If it's always four numbers, you shouldn't define the field as
nvarchar(50)
. You know it's never going to contain any "extended" characters, so you don't need the
n
prefix. You know the length will never be more than
4
, so you don't need room for
50
characters. And you know the length will never be
less than
4
, so you don't need a variable-length field.
Define the field as
char(4)
instead.
A better option would be to define four
bit
fields, and make the
PartDone
field a calculated column:
DECLARE @tmp TABLE
(
PartId int,
[first] bit,
[second] bit,
[third] bit,
[fourth] bit,
PartDone As
(
CASE WHEN [first] Is Null THEN '2' ELSE CAST([first] As char(1)) END
+ CASE WHEN [second] Is Null THEN '2' ELSE CAST([second] As char(1)) END
+ CASE WHEN [third] Is Null THEN '2' ELSE CAST([third] As char(1)) END
+ CASE WHEN [fourth] Is Null THEN '2' ELSE CAST([fourth] As char(1)) END
)
);
INSERT INTO @tmp (PartId, [first], [second], [third], [fourth])
VALUES
(555444, 0, 0, 1, NULL),
(911877, 0, NULL, NULL, 1)
;
SELECT
PartId,
PartDone,
CASE [first] WHEN 0 THEN 'no' WHEN 1 THEN 'yes' END As [first],
CASE [second] WHEN 0 THEN 'no' WHEN 1 THEN 'yes' END As [second],
CASE [third] WHEN 0 THEN 'no' WHEN 1 THEN 'yes' END As [third],
CASE [fourth] WHEN 0 THEN 'no' WHEN 1 THEN 'yes' END As [fourth]
FROM
@tmp
;