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

Untitled

By: a guest on Apr 25th, 2012  |  syntax: None  |  size: 1.19 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. Is there a SQL Statement that allows me to copy and insert existing rows but with one column change?
  2. Col1   Col2    Col3
  3.  
  4.   a       b       AA
  5.  
  6.   1       2       33
  7.        
  8. Col1   Col2    Col3
  9.  
  10.   a       b       **BB**
  11.  
  12.   1       2       **44**
  13.        
  14. INSERT INTO
  15.   myTable (
  16.     Col1,
  17.     Col2,
  18.     Col3
  19.   )
  20. SELECT
  21.   Col1,
  22.   Col2,               -- This is a specific example based on your comment.
  23.   Col3 + 6            -- This just adds 6 to the existing value, but any SQL
  24. FROM                  -- could actually go here, such as a CASE statement...
  25.   myTable
  26.        
  27. CASE WHEN Col3 = 'AA' THEN '**BB**'
  28.      WHEN Col3 = '33' THEN '**44**'
  29.                       ELSE 'Unknown'
  30. END,
  31.        
  32. INSERT INTO
  33.   myTable (
  34.     Col1,
  35.     Col2,
  36.     Col3
  37.   )
  38. SELECT
  39.   OldTable.Col1,
  40.   OldTable.Col2,
  41.   COALESCE(NewTable.Col3, 'Unknown')
  42. FROM
  43.   myTable     AS OldTable
  44. LEFT JOIN
  45.   lookup      AS NewTable
  46.     ON  OldTable.Col1 = NewTable.Col1
  47.     AND OldTable.Col2 = NewTable.Col2
  48.        
  49. INSERT INTO table_name( col1, col2, col3 )
  50.   SELECT col1,
  51.          col2,
  52.          (CASE WHEN col3 = 'AA'
  53.                  THEN 'BB'
  54.                WHEN col3 = '33'
  55.                  THEN '44'
  56.                ELSE null
  57.             END)
  58.     FROM table_name;