<p><strong>Edit</strong>:  Let me completely rephrase this, because I'm not sure there's an XML way like I was originally describing.</p>

<p><strong>Yet another edit</strong>: This needs to be a repeatable process, and it has to be able to be set up in a way that it can be called in C# code.</p>

<p>In database A, I have a set of tables, related by PKs and FKs.  A parent table, with child and grandchild tables, let's say.</p>

<p>I want to <strong>copy a set of rows from database A to database B</strong>, which has identically named tables and fields.  For each table, I want to insert into the same table in database B.  But I can't be constrained to use the same primary keys.  <strong>The copy routine must create new PKs</strong> for each row in database B, and must propagate those to the child rows.  I'm keeping the same relations between the data, in other words, but not the same exact PKs and FKs.</p>

<p>How would you solve this?  I'm open to suggestions.  SSIS isn't completely ruled out, but it doesn't look to me like it'll do this exact thing.  I'm also open to a solution in LINQ, or using typed DataSets, or using some XML thing, or just about anything that'll work in SQL Server 2005 and/or C# (.NET 3.5).  The best solution wouldn't require SSIS, and wouldn't require writing a lot of code.  But I'll concede that this "best" solution may not exist.</p>

<p>(I didn't make this task up myself, nor the constraints; this is how it was given to me.)</p>

[{'answer_id': 59378, 'author': 'jason saldo', 'author_id': 1293, 'author_profile': 'https://Stackoverflow.com/users/1293', 'pm_score': 0, 'selected': False, 'text': '<p>Dump the XML approach and use the import wizard / SSIS.</p>\n'}, {'answer_id': 59407, 'author': 'Josef', 'author_id': 5581, 'author_profile': 'https://Stackoverflow.com/users/5581', 'pm_score': 1, 'selected': False, 'text': '<p>First, let me say that SSIS is your best bet. But, to answer the question you asked...</p>\n\n<p>I don\'t believe you will be able to get away with creating new id\'s all around, although you could but you would need to take the original IDs to use for lookups.</p>\n\n<p>The best you can get is one insert statement for table. Here is an example of the code to do <code>SELECT</code>s to get you the data from your XML Sample:</p>\n\n<pre><code>declare @xml xml \nset @xml=\'&lt;People Key="1" FirstName="Bob" LastName="Smith"&gt;\n  &lt;PeopleAddresses PeopleKey="1" AddressesKey="1"&gt;\n    &lt;Addresses Key="1" Street="123 Main" City="St Louis" State="MO" ZIP="12345" /&gt;\n  &lt;/PeopleAddresses&gt;\n&lt;/People&gt;\n&lt;People Key="2" FirstName="Harry" LastName="Jones"&gt;\n  &lt;PeopleAddresses PeopleKey="2" AddressesKey="2"&gt;\n    &lt;Addresses Key="2" Street="555 E 5th St" City="Chicago" State="IL" ZIP="23456" /&gt;\n  &lt;/PeopleAddresses&gt;\n&lt;/People&gt;\n&lt;People Key="3" FirstName="Sally" LastName="Smith"&gt;\n  &lt;PeopleAddresses PeopleKey="3" AddressesKey="1"&gt;\n    &lt;Addresses Key="1" Street="123 Main" City="St Louis" State="MO" ZIP="12345" /&gt;\n  &lt;/PeopleAddresses&gt;\n&lt;/People&gt;\n&lt;People Key="4" FirstName="Sara" LastName="Jones"&gt;\n  &lt;PeopleAddresses PeopleKey="4" AddressesKey="2"&gt;\n    &lt;Addresses Key="2" Street="555 E 5th St" City="Chicago" State="IL" ZIP="23456" /&gt;\n  &lt;/PeopleAddresses&gt;\n&lt;/People&gt;\n\'\n\nselect t.b.value(\'./@Key\', \'int\') PeopleKey,\n    t.b.value(\'./@FirstName\', \'nvarchar(50)\') FirstName,\n    t.b.value(\'./@LastName\', \'nvarchar(50)\') LastName\nfrom @xml.nodes(\'//People\') t(b)\n\nselect t.b.value(\'../../@Key\', \'int\') PeopleKey,\n    t.b.value(\'./@Street\', \'nvarchar(50)\') Street,\n    t.b.value(\'./@City\', \'nvarchar(50)\') City,\n    t.b.value(\'./@State\', \'char(2)\') [State],\n    t.b.value(\'./@Zip\', \'char(5)\') Zip\nfrom \n@xml.nodes(\'//Addresses\') t(b)\n</code></pre>\n\n<p>What this does is take Nodes from the XML and parse out the data. To get the relational id from people we use ../../ to go up the chain.</p>\n'}, {'answer_id': 60031, 'author': 'Jonathan Allen', 'author_id': 5274, 'author_profile': 'https://Stackoverflow.com/users/5274', 'pm_score': 0, 'selected': False, 'text': "<p>By far the easiest way is Red Gate's SQL Data Compare. You can set it up to do just what you described in a minute or two.</p>\n"}, {'answer_id': 60678, 'author': 'Mike L', 'author_id': 4796, 'author_profile': 'https://Stackoverflow.com/users/4796', 'pm_score': 0, 'selected': False, 'text': "<p>I love Red Gate's SQL Compare and Data Compare too but it won't meet his requirements for the changing primary keys as far as I can tell.  </p>\n\n<p>If cross database queries/linked servers are an option you could do this with a stored procedure that copies the records from parent/child in DB A into temporary tables on DB B and then add a column for the new primary key in the temp child table that you would update after inserting the headers.  </p>\n\n<p>My question is if the records don't have the same primary key how do you tell if it's a new record? Is there some other candidate key? If these are new tables why can't they have the same primary key?</p>\n"}, {'answer_id': 71011, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>I have created the same thing with a set of stored procedures.</p>\n\n<p>Database B will have its own primary keys, but store Database A's primary keys, for debuging purposes. It means I can have more than one Database A!</p>\n\n<p>Data is copied via a linked server. Not too fast; SSIS is faster. But SSIS is not for beginners, and it is not easy to code something that works with changing source tables.</p>\n\n<p>And it is easy to call a stored procedure from C#.  </p>\n"}, {'answer_id': 71405, 'author': 'CJM', 'author_id': 6898, 'author_profile': 'https://Stackoverflow.com/users/6898', 'pm_score': 0, 'selected': False, 'text': "<p>I'd script it in a Stored Procedure, using Inserts to do the hard work. Your code will take the PKs from Table A (presumably via @@Scope_Identity) - I assume that the PK for Table A is an Identity field?</p>\n\n<p>You could use temporary tables, cursors or you might prefer to use the CLR - it might lend itself to this kind of operation.</p>\n\n<p>I'd be surprised to find a tool that could do this off the shelf with either a) pre-determined keys, or b) identity fields (clearly Tables B &amp; C don't have them).</p>\n"}, {'answer_id': 80413, 'author': 'Dr8k', 'author_id': 6014, 'author_profile': 'https://Stackoverflow.com/users/6014', 'pm_score': 0, 'selected': False, 'text': '<p>Are you clearing the destination tables each time and then starting again? That will make a big difference to the solution you need to implement. If you are doing a complete re-import each time then you could do something like the following:</p>\n\n<p>Create a temporary table or table variable to record the old and new primary keys for the parent table.</p>\n\n<p>Insert the parent table data into the destination and use the <a href="http://blogs.msdn.com/sqltips/archive/2005/06/13/OUTPUT-clause.aspx" rel="nofollow noreferrer">OUTPUT</a> clause to capture the new ID\'s and insert them with the old IDs into the temp table.\nNOTE: Using the output clause is efficient and allows you to do the insert in bulk without cycling through each record to be inserted.</p>\n\n<p>Insert the child table data. Join to the temp table to retrieve the new foreign key required.</p>\n\n<p>The above process could be done using T-SQL Script, C# code or SSIS. My preference would be for SSIS.</p>\n'}, {'answer_id': 89048, 'author': 'Dr8k', 'author_id': 6014, 'author_profile': 'https://Stackoverflow.com/users/6014', 'pm_score': 0, 'selected': False, 'text': '<p>If you are adding each time then you may need to keep a permanent table to track the relationship between source database primary keys and destination database primary keys (at least for the parent table). If you needed to keep this kind of data out of the destination database, you could get SSIS to store/retrieve it from some kind of logging database or even a flat file.</p>\n\n<p>You could probably avoid the above scenario if there is a combination of fields in the parent table that can be used to uniquely identify that record and therefore "find" the primary key for that record in the destination database. </p>\n'}, {'answer_id': 89310, 'author': 'Ryan Lundy', 'author_id': 5486, 'author_profile': 'https://Stackoverflow.com/users/5486', 'pm_score': 1, 'selected': True, 'text': "<p>I think most likely what I'm going to use is typed datasets.  It won't be a generalized solution; we'll have to regenerate them if any of the tables change.  But based on what I've been told, that's not a problem; the tables aren't expected to change much.</p>\n\n<p>Datasets will make it reasonably easy to loop through the data hierarchically and refresh PKs from the database after insert.</p>\n"}, {'answer_id': 153154, 'author': 'kristof', 'author_id': 3241, 'author_profile': 'https://Stackoverflow.com/users/3241', 'pm_score': 0, 'selected': False, 'text': '<p>When dealing with similar tasks I simply created a set of stored procedures to do the job.</p>\n\n<p>As the task that you specified is pretty custom, you are not likely to find "ready to use" solution.</p>\n\n<p>Just to give you some hints:</p>\n\n<ul>\n<li>If the databases are on different servers use linked servers so you can access both source and destination tables simply through TSQL</li>\n</ul>\n\n<p>In the stored procedure:</p>\n\n<ul>\n<li>Identify the parent items that need to be copied - you said that the primary keys are different so you need to use unique constraints instead (you should be able to define them if the tables are normalised)</li>\n<li>Identify the child items that need to be copied based on the identified parents, to check if some of them are already in the destination db use the unique constraints approach again</li>\n<li>Identify the grandchild items (same logic as with parent-child)</li>\n<li>Copy data over starting with the lowest level (grandchildren, children, parents)</li>\n</ul>\n\n<p>There is no need for cursors etc, simply store the immediate results in the temporary table (or table variable if working within one stored procedure)</p>\n\n<p>That approach worked for me pretty well.</p>\n\n<p>You can of course add parameter to the main stored procedure so you can either copy all new records or only ones that you specify.</p>\n\n<p>Let me know if that is of any help.</p>\n'}, {'answer_id': 153178, 'author': 'Sklivvz', 'author_id': 7028, 'author_profile': 'https://Stackoverflow.com/users/7028', 'pm_score': 2, 'selected': False, 'text': '<p>I think the SQL Server utility <a href="http://weblogs.sqlteam.com/mladenp/archive/2007/03/03/60125.aspx" rel="nofollow noreferrer">tablediff.exe</a> might be what you are looking for.</p>\n\n<p>See also <a href="https://stackoverflow.com/questions/121243/hidden-features-of-sql-server">this thread</a>.</p>\n'}]
['https://Stackoverflow.com/questions/59357', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5486/']