Update NULL Values From Previous Non-Null Value in A Column


DECLARE @TAB TABLE ( CALDATE DATETIME,
CODE VARCHAR(20))

INSERT INTO @TAB
SELECT 41194,’3243861′ UNION ALL
SELECT 41193,NULL UNION ALL
SELECT 41192,NULL UNION ALL
SELECT 41189,’3243862′ UNION ALL
SELECT 41188,NULL UNION ALL
SELECT 41187,’3243862′ UNION ALL
SELECT 41184,’3243862′ UNION ALL
SELECT 41183,’3243862′ UNION ALL
SELECT 41182,NULL UNION ALL
SELECT 41179,NULL UNION ALL
SELECT 41178,’3243863′ UNION ALL
SELECT 41177,NULL UNION ALL
SELECT 41176,NULL

;with mycte as
(
SELECT CALDATE,Code, row_number()over(order by caldate desc) rn
FROM @Tab A)

SELECT m.CALDATE,d.Code FROM mycte m
OUTER APPLY (SELECT TOP 1 * FROM mycte
WHERE rn<= m.rn AND Code IS NOT NULL
ORDER BY rn desc) d

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s