I am looking for building a query to replace null value with previous available values.can somebody help.Here is the table currently looking like
11/30/2015
Maybe something like the code given below.
Note: Code not tested. Also, this code needs to consider if you need the previous value based on the ID column or any other requirement like that.
CREATE TABLE Table1 (Date1 VARCHAR(10), ID VARCHAR(10), Class VARCHAR(10), ID2 INT);
INSERT INTO Table1 Values ('11/30/2015', 'ID1', 'ClassName', 1);
INSERT INTO Table1 Values (NULL, 'ID1', 'ClassName', 2);
INSERT INTO Table1 Values (NULL, 'ID1', 'ClassName', 3);
INSERT INTO Table1 Values (NULL, 'ID1', 'ClassName', 4);
INSERT INTO Table1 Values ('12/31/2015', 'ID1', 'ClassName', 5);
INSERT INTO Table1 Values (NULL, 'ID1', 'ClassName', 6);
INSERT INTO Table1 Values (NULL, 'ID1', 'ClassName', 7);
CREATE TABLE Table2 (Date1 VARCHAR(10), ID VARCHAR(10), Class VARCHAR(10), ID2 INT);
DECLARE @Date1 VARCAHR(10), @ID1 VARCHAR(10), @Class VARCHAR(10), @ID2 INT;
DECLARE @TempDate1 VARCAHR(10); --set default if first record is null
DECLARE CURSOR MYCUR FOR
SELECT Date1, ID1, Class, ID2
FROM Table1;
OPEN MYCUR
FETCH NEXT FROM MYCUR INTO @Date1, @ID1, @Class, @ID2
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@Date1 IS NOT NULL)
BEGIN
@TempDate1=@Date1
END
INSERT INTO Table2 VALUES(@TempDate1, @ID1, @Class, @ID2)
FETCH NEXT FROM MYCUR INTO @Date1, @ID1, @Class, @ID2
END
CLOSE MYCUR
DEALLOCATE MYCUR
SELECT * FROM Table2