Share via

Unpivot not return null value?

Riley 380 Reputation points
2023-05-31T06:16:42.47+00:00

I want NULL value still in the output.

See below sample:

Declare @tbl table (id int, val1 int,val2 int,val3 int)
insert into @tbl values
(1,23,null,34),(2,16,74,25),(3,33,24,null)

select *
from @tbl
Unpivot(val for val_type in ([val1],[val2],[val3]))u

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

Answer accepted by question author

LiHongMSFT-4306 31,621 Reputation points
2023-05-31T06:23:24.03+00:00

Hi @Siver

You could use Cross Apply like this:

SELECT id,C.*
FROM @tbl CROSS APPLY(VALUES(val1,'val1'),(val2,'val2'),(val3,'val3'))C(val,valtype)

Best regards,

Cosmog Hong

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.