3

I have table Salesorder and structure of the table is like this.

Create table Salesorder(SOID int identity, quantity numeric(18,2))

Values in the table is as mentioned below.

insert into Salesorder values(100)
insert into Salesorder values(Null)
insert into Salesorder values(200)
insert into Salesorder values(300)
insert into Salesorder values(Null)
insert into Salesorder values(Null)
insert into Salesorder values(500)
insert into Salesorder values(Null)

So, I want to update this table in that manner so that if I execute select query, I should find below result.

Expected Output:

100
100
200
300
300
300
500
500

It means all null values should be updated with the previous not null values.

shA.t
  • 16,580
  • 5
  • 54
  • 111

3 Answers3

3

Here is working statement:

Update so1
Set quantity = (select top 1 quantity
               from Salesorder so2 
               where so2.quantity is not null and
                     so2.SOID < so1.SOID 
               order by SOID desc)
From Salesorder so1
Where quantity is null;

Fiddle http://sqlfiddle.com/#!6/5a643/30

Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
1

This query will UPDATE as expected,

UPDATE Salesorder1 SET Salesorder1.quantity =
CASE WHEN Salesorder1.quantity IS NULL 
    THEN (
            SELECT TOP 1 SalesOrder2.quantity 
            FROM Salesorder AS SalesOrder2
            WHERE 
                SalesOrder2.quantity IS NOT NULL AND 
                SalesOrder2.SOID < SalesOrder1.SOID 
            ORDER BY SalesOrder2.SOID DESC
        )
    END
 FROM Salesorder AS SalesOrder1
 WHERE SalesOrder1.quantity IS NULL

The CASE statement

SalesOrder2.quantity IS NOT NULL 
AND SalesOrder2.SOID < SalesOrder1.SOID 
ORDER BY SalesOrder2.SOID DESC

replaces NULL values with the previous value and the WHERE clause gives the NOT NULL value with descending order.

SelvaS
  • 2,105
  • 1
  • 22
  • 31
0

If You want to get the previous value in your insert statement:

INSERT INTO SalesOrder 
VALUES (ISNULL(?, (
    SELECT quantity
    FROM SalesOrder s
    WHERE s.SOID = (SELECT MAX(si.SOID)
                    FROM SalesOrder si))
shA.t
  • 16,580
  • 5
  • 54
  • 111