Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 1st, 2012  |  syntax: None  |  size: 0.77 KB  |  hits: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Update column value of one row from other rows
  2. sno name   pid amount total
  3. 1   Arif    0   100    null
  4. 2   Raj     1   200    null
  5. 3   Ramesh  2   100    null
  6. 4   Pooja   2   100    null
  7. 5   Swati   3   200    null
  8. 6   King    4   100    null
  9.        
  10. WITH hierarchified AS (
  11.   SELECT
  12.     sno,
  13.     amount,
  14.     hierarchyID = CAST(sno AS varchar(500))
  15.   FROM yourTable
  16.   WHERE pid = 0
  17.   UNION ALL
  18.   SELECT
  19.     t.sno,
  20.     t.amount,
  21.     hierarchyID = CAST(h.hierarchyID + '/' + RTRIM(t.sno) AS varchar(500))
  22.   FROM yourTable t
  23.     INNER JOIN hierarchified h ON t.pid = h.sno
  24. )
  25. UPDATE yourTable
  26. SET total = t.amount + ISNULL(
  27.   (
  28.     SELECT SUM(amount)
  29.     FROM hierarchified
  30.     WHERE hierarchyID LIKE h.hierarchyID + '/%'
  31.   ),
  32.   0
  33. )
  34. FROM yourTable t
  35. INNER JOIN hierarchified h ON t.sno = h.sno;