<p>I know that that is not a question... erm anyway HERE is the question.</p>

<p>I have inherited a database that has 1(one) table in that looks much like this. Its aim is to record what species are found in the various (200 odd) countries.</p>

<pre><code>ID 
Species
Afghanistan
Albania
Algeria
American Samoa
Andorra
Angola
....
Western Sahara
Yemen
Zambia
Zimbabwe
</code></pre>

<p>A sample of the data would be something like this</p>

<pre><code>id Species Afghanistan Albania American Samoa
1  SP1         null     null        null
2  SP2          1         1         null
3  SP3         null      null         1
</code></pre>

<p>It seems to me this is a typical many to many situation and I want 3 tables.
Species, Country, and SpeciesFoundInCountry</p>

<p>The link table (SpeciesFoundInCountry) would have foreign keys in both the species and Country tables.</p>

<p>(It is hard to draw the diagram!)</p>

<pre><code>Species
SpeciesID  SpeciesName

Country
CountryID CountryName

SpeciesFoundInCountry
CountryID SpeciesID
</code></pre>

<p>Is there a magic way I can generate an insert statement that will get the CountryID from the new Country table based on the column name and the SpeciesID where there is a 1 in the original mega table?</p>

<p>I can do it for one Country (this is a select to show what I want out)</p>

<pre><code>SELECT Species.ID, Country.CountryID
FROM Country, Species
WHERE (((Species.Afghanistan)=1)) AND (((Country.Country)="Afghanistan"));
</code></pre>

<p>(the mega table is called species)</p>

<p>But using this strategy I would need to do the query for each column in the original table. </p>

<p>Is there a way of doing this in sql?</p>

<p>I guess I can OR a load of my where clauses together and write a script to make the sql, seems inelegant though!</p>

<p>Any thoughts (or clarification required)?</p>

[{'answer_id': 76999, 'author': 'Sarien', 'author_id': 1994377, 'author_profile': 'https://Stackoverflow.com/users/1994377', 'pm_score': 3, 'selected': False, 'text': '<p>Why do you want to do it in SQL? Just write a little script that does the conversion.</p>\n'}, {'answer_id': 77017, 'author': 'nsayer', 'author_id': 13757, 'author_profile': 'https://Stackoverflow.com/users/13757', 'pm_score': 1, 'selected': False, 'text': "<p>You're probably going to want to create replacement tables in place. The script sort of depends on the scripting language you have available to you, but you should be able to create the country ID table simply by listing the columns of the table you have now. Once you've done that, you can do some string substitutions to go through all of the unique country names and insert into the speciesFoundInCountry table where the given country column is not null.</p>\n"}, {'answer_id': 77028, 'author': 'Leigh Caldwell', 'author_id': 3267, 'author_profile': 'https://Stackoverflow.com/users/3267', 'pm_score': 4, 'selected': True, 'text': "<p>I would use a script to generate all the individual queries, since this is a one-off import process.</p>\n\n<p>Some programs such as Excel are good at mixing different dimensions of data (comparing column names to data inside rows) but relational databases rarely are.</p>\n\n<p>However, you might find that some systems (such as Microsoft Access, surprisingly) have convenient tools which you can use to normalise the data. Personally I'd find it quicker to write the script but your relative skills with Access and scripting might be different to mine.</p>\n"}, {'answer_id': 77038, 'author': 'StubbornMule', 'author_id': 13341, 'author_profile': 'https://Stackoverflow.com/users/13341', 'pm_score': 2, 'selected': False, 'text': '<p>When I run into these I write a script to do the conversion rather than trying to do it in SQL.   It is typically much faster and easier for me.  Pick any language you are comfortable with.</p>\n'}, {'answer_id': 77039, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 1, 'selected': False, 'text': "<p>You could probably get clever and query the system tables for the column names, and then build a dynamic query string to execute, but honestly that will probably be uglier than a quick script to generate the SQL statements for you.</p>\n\n<p>Hopefully you don't have too much dynamic SQL code that accesses the old tables buried in your codebase.  That could be the <em>really</em> hard part.</p>\n"}, {'answer_id': 77054, 'author': 'Tom Ritter', 'author_id': 8435, 'author_profile': 'https://Stackoverflow.com/users/8435', 'pm_score': 1, 'selected': False, 'text': '<p>In SQL Server this will generate your custom select you demonstrate.  You can extrapolate to an insert</p>\n\n<blockquote>\n<pre><code>select \n  \'SELECT Species.ID, Country.CountryID FROM Country, Species WHERE (((Species.\' + \n c.name + \n \')=1)) AND (((Country.Country)="\' +\n c.name + \n \'"))\'\nfrom syscolumns c\ninner join sysobjects o\non o.id = c.id\nwhere o.name = \'old_table_name\'\n</code></pre>\n</blockquote>\n'}, {'answer_id': 77068, 'author': 'Mitchel Sellers', 'author_id': 13279, 'author_profile': 'https://Stackoverflow.com/users/13279', 'pm_score': 1, 'selected': False, 'text': "<p>As with the others I would most likely just do it as a one time quick fix in whatever manner works for you.</p>\n\n<p>With these types of conversions, they are one off items, quick fixes, and the code doesn't have to be elegant, it just has to work.  For these types of things I have done it many ways.</p>\n"}, {'answer_id': 77070, 'author': 'eulerfx', 'author_id': 13855, 'author_profile': 'https://Stackoverflow.com/users/13855', 'pm_score': 1, 'selected': False, 'text': '<p>If this is SQL Server, you can use the sys.columns table to find all of the columns of the original table. Then you can use dynamic SQL and the pivot command to do what you want. Look those up online for syntax.</p>\n'}, {'answer_id': 77149, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>I would definitely agree with your suggestion of writing a small script to produce your SQL with a query for every column.</p>\n\n<p>In fact your script could have already been finished in the time you've spent thinking about this magical query (that you would use only one time and then throw away, so what's the use in making it all magicy and perfect)</p>\n"}, {'answer_id': 77283, 'author': 'digiguru', 'author_id': 5055, 'author_profile': 'https://Stackoverflow.com/users/5055', 'pm_score': 2, 'selected': False, 'text': '<p>If this was SQL Server, you\'d use the Unpivot commands, but looking at the tag you assigned it\'s for access - am I right?</p>\n\n<p>Although there is a  <a href="http://www.blueclaw-db.com/accessquerysql/pivot_query.htm" rel="nofollow noreferrer">pivoting command in access</a>, there is no reverse statement.</p>\n\n<p>Looks like it can be done with a complex join. Check this <a href="http://weblogs.sqlteam.com/jeffs/archive/2008/04/23/unpivot.aspx" rel="nofollow noreferrer">interesting article</a> for a lowdown on how to unpivot in a select command.</p>\n'}, {'answer_id': 77610, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>I would make it a three step process with a slight temporary modification to your SpeciesFoundInCountry table.  I would add a column to that table to store the Country name.  Then the steps would be as follows.</p>\n\n<p>1) Create/Run a script that walks columns in the source table and creates a record in SpeciesFoundInCountry for each column that has a true value. This record would contain the country name.\n2) Run a SQL statement that updates the SpeciesFoundInCountry.CountryID field by joining to the Country table on Country Name.\n3) Cleanup the SpeciesFoundInCountry table by removing the CountryName column.</p>\n\n<p>Here is a little MS Access VB/VBA pseudo code to give you the gist</p>\n\n<pre><code>Public Sub CreateRelationshipRecords()\n\n  Dim rstSource as DAO.Recordset\n  Dim rstDestination as DAO.Recordset\n  Dim fld as DAO.Field\n  dim strSQL as String\n  Dim lngSpeciesID as Long\n\n  strSQL = "SELECT * FROM [ORIGINALTABLE]"\n  Set rstSource = CurrentDB.OpenRecordset(strSQL)\n  set rstDestination = CurrentDB.OpenRecordset("SpeciesFoundInCountry")\n\n  rstSource.MoveFirst\n\n  \' Step through each record in the original table\n  Do Until rstSource.EOF\n    lngSpeciesID = rstSource.ID\n    \' Now step through the fields(columns). If the field\n    \' value is one (1), then create a relationship record\n    \' using the field name as the Country Name\n    For Each fld in rstSource.Fields\n      If fld.Value = 1 then\n        with rstDestination\n          .AddNew\n          .Fields("CountryID").Value = Null\n          .Fields("CountryName").Value = fld.Name\n          .Fields("SpeciesID").Value = lngSpeciesID\n          .Update\n        End With\n      End IF\n    Next fld  \n    rstSource.MoveNext\n  Loop\n\n  \' Clean up\n  rstSource.Close\n  Set rstSource = nothing\n  ....\n\nEnd Sub\n</code></pre>\n\n<p>After this you could run a simple SQL statement to update the CountryID values in the SpeciesFoundInCountry table.</p>\n\n<p>UPDATE SpeciesFoundInCountry INNER JOIN Country ON SpeciesFoundInCountry.CountryName = Country.CountryName SET SpeciesFoundInCountry.CountryID = Country.CountryID;</p>\n\n<p>Finally, all you have to do is cleanup the SpeciesFoundInCountry table by removing the CountryName column.</p>\n\n<p>****SIDE NOTE:  I have found it usefull to have country tables that also include the ISO abbreviations (country codes).  Occassionally they are used as Foreign Keys in other tables so that a join to the Country table does not have to be included in queries.</p>\n\n<p>For more info:  <a href="http://en.wikipedia.org/wiki/Iso_country_codes" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Iso_country_codes</a></p>\n'}, {'answer_id': 77633, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Sorry, but the bloody posting parser removed the whitespace and formatting on my post.  It makes it a log harder to read.</p>\n'}, {'answer_id': 78130, 'author': 'CindyH', 'author_id': 12897, 'author_profile': 'https://Stackoverflow.com/users/12897', 'pm_score': 1, 'selected': False, 'text': '<p>@stomp:</p>\n\n<p>Above the box where you type the answer, there are several buttons.  The one that is 101010 is a code sample.  You select all your text that is code, and then click that button.  Then it doesn\'t get messed with much.</p>\n\n<pre><code>cout&gt;&gt;"I don\'t know C"\ncout&gt;&gt;"Hello World"\n</code></pre>\n'}, {'answer_id': 78249, 'author': 'Fionnuala', 'author_id': 2548, 'author_profile': 'https://Stackoverflow.com/users/2548', 'pm_score': 1, 'selected': False, 'text': '<p>I would use a Union query, very roughly:</p>\n\n<pre><code>Dim db As Database\nDim tdf As TableDef\n\nSet db = CurrentDb\n\nSet tdf = db.TableDefs("SO")\n\nstrSQL = "SELECT ID, Species, """ &amp; tdf.Fields(2).Name _\n    &amp; """ AS Country, [" &amp; tdf.Fields(2).Name &amp; "] AS CountryValue FROM SO "\n\nFor i = 3 To tdf.Fields.Count - 1\n    strSQL = strSQL &amp; vbCrLf &amp; "UNION SELECT ID, Species, """ &amp; tdf.Fields(i).Name _\n    &amp; """ AS Country, [" &amp; tdf.Fields(i).Name &amp; "] AS CountryValue FROM SO "\nNext\n\ndb.CreateQueryDef "UnionSO", strSQL\n</code></pre>\n\n<p>You would then have a view that could be appended to your new design.</p>\n'}, {'answer_id': 78348, 'author': 'Gaurav', 'author_id': 13492, 'author_profile': 'https://Stackoverflow.com/users/13492', 'pm_score': 1, 'selected': False, 'text': "<p>When I read the title 'bad BAD database design', I was curious to find out how bad it is. You didn't disappoint me :)</p>\n\n<p>As others mentioned, a script would be the easiest way. This can be accomplished by writing about 15 lines of code in PHP.</p>\n\n<pre><code>SELECT * FROM ugly_table;\nwhile(row)\nforeach(row as field =&gt; value)\nif(value == 1)\nSELECT country_id from country_table WHERE country_name = field;\n\nif(field == 'Species')\nSELECT species_id from species_table WHERE species_name = value;\n\nINSERT INTO better_table (...)\n</code></pre>\n\n<p>Obviously this is pseudo code and will not work as it is. You can also populate the countries and species table on the fly by adding insert statements here.</p>\n"}, {'answer_id': 78464, 'author': 'user14336', 'author_id': 14336, 'author_profile': 'https://Stackoverflow.com/users/14336', 'pm_score': 1, 'selected': False, 'text': "<p>Sorry, I've done very little Access programming but I can offer some guidance which should help.</p>\n\n<p>First lets walk through the problem.\nIt is assumed that you will typically need to generate multiple rows in SpeciesFoundInCountry for every row in the original table. In other words species tend to be in more then one country. This is actually easy to do with a Cartesian product, a join with no join criteria. </p>\n\n<p>To do a Cartesian product you will need to create the Country table. The table should have the country_id from 1 to N (N being the number of unique countries, 200 or so) and country name. To make life easy just use the numbers 1 to N in column order. That would make Afghanistan 1 and Albania 2 ... Zimbabwe N. You should be able to use the system tables to do this.</p>\n\n<p>Next create a table or view from the original table which contains the species and a sting with a 0 or 1 for each country. You will need to convert the null, not null to a text 0 or 1 and concatenate all of the values into a single string. A description of the table and a text editor with regular expressions should make this easy. Experiment first with a single column and once that's working edit the create view/insert with all of the columns.</p>\n\n<p>Next join the two tables together with no join criteria. This will give you a record for every species in every country, you're almost there.</p>\n\n<p>Now all you have to do is filter out the records which are not valid, they will have a zero in the corresponding location in the string. Since the country table's country_code column has the substring location all you need to do is filter out the records where it's 0.</p>\n\n<pre><code>where substring(new_column,country_code) = '1'\n</code></pre>\n\n<p>You will still need to create the species table and join to that </p>\n\n<pre><code>where a.species_name = b.species_name\n</code></pre>\n\n<p>a and b are table aliases.</p>\n\n<p>Hope this help</p>\n"}, {'answer_id': 78505, 'author': 'user14336', 'author_id': 14336, 'author_profile': 'https://Stackoverflow.com/users/14336', 'pm_score': 1, 'selected': False, 'text': '<p>OBTW,</p>\n\n<p>If you have queries that already run against the old table you will need to create a view which replicates the old tables using the new tables. You will need to do a group by to denormalize the tables. </p>\n\n<p>Tell your users that the old table/view will not be supported in the future and all new queries or updates to older queries will have to use the new tables.</p>\n'}, {'answer_id': 119036, 'author': 'Glenn M', 'author_id': 61669, 'author_profile': 'https://Stackoverflow.com/users/61669', 'pm_score': 1, 'selected': False, 'text': '<p>If I ever have to create a truckload of similar SQL statements and execute all of them, I often find Excel is very handy. Take your original query. If you have a country list in column A and your SQL statement in column B, formated as text (in quotes) with cell references inserted where the country appears in the sql</p>\n\n<p>e.g. ="INSERT INTO new_table SELECT    ...    (species." &amp; A1 &amp; ")=    ...    ));"</p>\n\n<p>then just copy the formula down to create 200 different SQL statements, copy/paste the column to your editor and hit F5. You can of course do this with as many variables as you want.</p>\n'}, {'answer_id': 197683, 'author': 'AJ.', 'author_id': 7211, 'author_profile': 'https://Stackoverflow.com/users/7211', 'pm_score': 1, 'selected': False, 'text': '<p>This is (hopefully) a one-off exercise, so an inelegant solution might not be as bad as it sounds.  </p>\n\n<p>The problem (as, I\'m sure you\'re only too aware!) is that at some point in your query you\'ve got to list all those columns.  :(  The question is, what is the most elegant way to do this?  Below is my attempt.  It looks unwieldy because there are so many columns, but it might be what you\'re after, or at least it might point you in the right direction.  </p>\n\n<h2>Possible SQL Solution:</h2>\n\n<pre><code>/* if you have N countries */\nCREATE TABLE Country\n(id    int, \n name  varchar(50)) \n\nINSERT Country\n      SELECT 1, \'Afghanistan\'\nUNION SELECT 2, \'Albania\', \nUNION SELECT 3, \'Algeria\' ,\nUNION SELECT 4, \'American Samoa\' ,\nUNION SELECT 5, \'Andorra\' ,\nUNION SELECT 6, \'Angola\' ,\n...\nUNION SELECT N-3, \'Western Sahara\', \nUNION SELECT N-2, \'Yemen\', \nUNION SELECT N-1, \'Zambia\', \nUNION SELECT N, \'Zimbabwe\', \n\n\n\nCREATE TABLE #tmp\n(key        varchar(N),  \n country_id int) \n/* "key" field needs to be as long as N */  \n\n\nINSERT #tmp \nSELECT \'1________ ... _\', \'Afghanistan\' \n/* \'1\' followed by underscores to make the length = N */\n\nUNION SELECT \'_1_______ ... ___\', \'Albania\'\nUNION SELECT \'__1______ ... ___\', \'Algeria\'\n...\nUNION SELECT \'________ ... _1_\', \'Zambia\'\nUNION SELECT \'________ ... __1\', \'Zimbabwe\'\n\nCREATE TABLE new_table\n(country_id int, \nspecies_id int) \n\nINSERT new_table\nSELECT species.id, country_id\nFROM   species s , \n       #tmp    t\nWHERE  isnull( s.Afghanistan, \' \' ) +  \n       isnull( s.Albania, \' \' ) +  \n       ... +  \n       isnull( s.Zambia, \' \' ) +  \n       isnull( s.Zimbabwe, \' \' ) like t.key \n</code></pre>\n\n<h2>My Suggestion</h2>\n\n<p>Personally, I would not do this.  I would do a quick and dirty solution like the one to which you allude, except that I would hard-code the country ids (because you\'re only going to do this once, right?  And you can do it right after you create the country table, so you know what all the IDs are): </p>\n\n<pre><code>INSERT new_table SELECT Species.ID, 1 FROM Species WHERE Species.Afghanistan = 1 \nINSERT new_table SELECT Species.ID, 2 FROM Species WHERE Species.Albania= 1 \n...\nINSERT new_table SELECT Species.ID, 999 FROM Species WHERE Species.Zambia= 1 \nINSERT new_table SELECT Species.ID, 1000 FROM Species WHERE Species.Zimbabwe= 1 \n</code></pre>\n'}, {'answer_id': 225462, 'author': 'Walter Mitty', 'author_id': 19937, 'author_profile': 'https://Stackoverflow.com/users/19937', 'pm_score': 1, 'selected': False, 'text': '<p>When I\'ve been faced with similar problems,  I\'ve found it convenient to generate a script that generates SQL scripts.  Here\'s the sample you gave, abstracted to use %PAR1% in place of Afghanistan.</p>\n\n<pre><code>SELECT Species.ID, Country.CountryID\nFROM Country, Species\nWHERE (((Species.%PAR1%)=1)) AND (((Country.Country)="%PAR1%"))\nUNION\n</code></pre>\n\n<p>Also the key word union has been added as a way to combine all the selects.</p>\n\n<p>Next, you need a list of countries, generated from your existing data:</p>\n\n<p>Afghanistan\nAlbania\n.\n,\n.</p>\n\n<p>Next you need a script that can iterate through the country list, and for each iteration,\nproduce an output that substitutes Afghanistan for %PAR1% on the first iteration,  Albania for the second iteration and so on.  The algorithm is just like mail-merge in a word processor.  It\'s a little work to write this script.  But, once you have it, you can use it in dozens of one-off projects like this one.</p>\n\n<p>Finally, you need to manually change the last "UNION" back to a semicolon.  </p>\n\n<p>If you can get Access to perform this giant union,  you can get the data you want in the form you want, and insert it into your new table.</p>\n'}]
['https://Stackoverflow.com/questions/76967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5552/']