Mike Online
  • Home
  • Vids & Photos
  • Guitar
    • Recordings >
      • My recordings
      • The CassTrators (MySpace)
    • Song chords >
      • Maggie May
      • Bob Dylan
      • Stars
      • Sunhee
    • Guitar tuner
  • Computing
    • QlikView
    • VBA & Excel
    • Visual Basic
    • SQL Server
    • Password Cracker >
      • ExcelFileHacker
  • Downloads
  • More...
    • Sidney Barrett
    • Wine >
      • Mr CCJ Berry - Blackberry Wine
      • Victory Blackberry Wine
      • Results
      • Links
    • Pottery >
      • Guides
      • Our Pottery >
        • Sunny's work...
        • Glaze - before & after
      • Links
    • Me... live
    • Jukebox
    • Education >
      • ESL
      • Academic writing
      • Korean
    • Calligraphy
    • TimesTables
    • App Dev
    • Links
    • Contact me

Creating new records based on multi-valued fields

So... if you have a 'products' table like this:

Product    Cost     Division
A1            20       A,B,C
A2            30       A,B,C
A3            40       B,C,D
A4            50       C

but you need it to be in this format

Product    Cost     Division
A1            20       A
A1            20       B
A1            20       C
A2            30       A
A2            30       B
A2            30       C
A3            40       B
A3            40       C
A3            40       D
A4            50       C

It is very time consuming to do manually (I tried) much better to use this cunning trick.

1 - Identify the multi-valued values in the products table that you'd like to change (something like this):

     select distinct Division from Products
     where len(division) > 1

2 - Put these distinct values in a new table called DivisionFix extracting out each individual division in
     a new record. So the DivisionFix table will look like this:

      DivGroup    NewDiv
       A,B,C          A
       A,B,C          B
       A,B,C          C
       B,C,D          B
       B,C,D          C
       B,C,D          D
 
3 - Join the Products table to the DivisionFix table to create the extra records and put that into a new Products 
     table:
     select * into Products_New from Products P left outer join DivisionFix D on P.Division = D.DivGroup

4 - Update the division field = NewDiv where there is a new division:
      update Products_New
      set division = coalesce (newdiv, division)

5 - Finally either truncate your original 'Products' table and extract all records from 'Products_New'
     or rename your 'Products' table to 'Products_BU' and then rename 'Products_new' to ''Products' to replace it
     (remember to delete the extra columns (DivGroup and NewDiv) and recreate any indexes etc)


Powered by Create your own unique website with customizable templates.