Database table copying - sql-server-2008

I am trying to rectify a previous database creation with tables that contains data that needs to be saved. Instead of recreating a completely new database since some of the tables are still reusable, I need to split a table that exists into 2 new tables which I have done. Now I am trying to insert the data into the 2 new tables and because of duplicate data in the old table I am having a hard time doing this.
Old table structure:
ClientProjects clientId PK
clientName
clientProj
hashkey MD5 (clientname and clientProj)
new table structures:
client clientId PK
clientName
projects queryId PK
clientId PK
projectName
I hope this makes sense. The problem is that in the old table for example you have clients with multiple clientIds.

Supposing your clientName is unique you could so something like:
INSERT client (clientId, clientName)
SELECT MAX(clientID), clientName FROM oldTable GROUP BY clientName;
INSERT project (clientId, projectName)
SELECT n.clientId, o.projectName from client n
INNER JOIN oldTable o on o.clientName = n.clientName;

Related

MySql load file script and 2 tables

So I have 2 tables, one is an contact table like
ContactId BigInt PK
Name varchar
Phone varchar
Address varchar
and a second table Vendor
CompanyName varchar
ContactId BigIn FK
I want to load vendors into the tables such that
When I load vendors with a CSV it will put them in the contact table and load them into the vendor table
123423234, bob smith, 333-444-5555, 123 stree dr., CompanyOne
123123234, john doe, 444-333-2222, 423 SomeStreet st., Another Company
I kept the tables small and simple for the post, yes there is more but the key here is I need to use the ContactID from the contact table in the Vendor table. and I want to load them both from the same cvs. I know how to do this if it was just the one table but not sure with the 2 tables.
Thanks!
You may be able to do this with all SQL, or it might require/be easier with a scripting language like PHP. But here is the basic pseudo code idea.
CREATE an unnormalized table that your CSV file can fit into pretty directly (we'll call it tempTable). Then put the data from the CSV into there. (Pretty sure this will require some scripting).
Insert contact info into contact table:
INSERT INTO contact (name, phone, address) (SELECT DISTINCT name, phone, address FROM tempTable);
Add a contactID column to tempTable and update it with the IDs from the contacts table by JOINing:
UPDATE tempTable JOIN contact ON
tempTable.name = contact.name
AND tempTable.phone = contact.phone
AND tempTable.address = contact.address
SET tempTable.contactID = contact.contactID
Then INSERT into vendor much like the way we inserted in to contact:
INSERT INTO VENDOR (companyName, contactID) (SELECT company, contactID FROM tempTable);

inserting data into a table that has a many to many relationship

I am working on an assignment and need your help with the following in SQL database:-
I have 3 tables
Product
LintItem
Invoice
LineItem is a bride table and I need to insert data into LineItem but it requires ProductID and InvoiceNumber.
In my case the Invoice table is emppty and it will be filled from the data that LineItem table passes.
The problem is how can I create an invoice before having the data from the lineItem table?
I am using these table for online shopping cart.
It's really hard for me to explain this problem. Hope you understand it, Thanks!
It sounds like you have a foreign key constraint forcing the existence of a Invoice record prior to inserting your line item records. It is hard to say exactly, based on the phrasing of your question but could be something like.
--Table variable to hold line items
DECLARE #lineItems TABLE
(
InvoiceNumber INT,
Quantity INT
)
INSERT INTO #lineitems VALUES(1,1)
INSERT INTO #lineitems VALUES(1,2)
--ADD INVOICE RECORD FIRST AND SUM Quantities etc....
INSERT INTO Invoice
SELECT InvoiceNumber,SUM(Quantity)
FROM #lineItems
GROUP BY InvoiceNumber
--NOW YOU CAN ADD LINE ITEMS
INSERT INTO LineItems SELECT * FROM #lineItems
This is a pattern you could use if that was your goal.
If you are wanting to insert these LineItems on the fly as the user is clicking Add from the webpage. I wouldn't use your LineItem SQL table for caching this way. Without knowing anything about your application it is hard to say but you really should be caching this data in the HTTP session or in the client as (array,json, local storage etc..). If you were to choose to do this as an SQL table just make a new LineItem without the constraints and then similarly per above you can use that table to insert into your LineItem table.

MySQL - insert into with foreign key index

Here is the scenario:
I have 2 tables and 2 temporary tables. Before I insert user data to the official tables, I insert them to a temp table to let them do the checks. There is a company table with company info, and a contact table that has contact info. The contact table has a field called company_id which is a foreign key index for the company table.
Temp tables are set up the same way.
I want to do something like: INSERT INTO company () SELECT * FROM temp_company; and INSERT INTO contact () SELECT * FROM temp_contact
My question is, how do I transfer the foreign key from the temp_company to the newly inserted id on the company table using a statement like this? Is there a way to do it?
Currently I am:
grabbing the temp rows
going one by one and inserting them
grabbing the last insert id
then inserting the contacts afterwards with the new last insert id
I just don't know if that is the most efficient way. Thanks!
if you have the same number of columns in both tables and then you should just be able to use the syntax you have there? Just take out the (). Just make sure there aren't any duplicate primary keys:
INSERT INTO company SELECT * FROM temp_company;
INSERT INTO contact SELECT * FROM temp_contact;
You can also specifically specify the columns that get inserted, this way you can specify exactly which column you insert as the new ID.
INSERT INTO company (`ID`,`col_1`,...,`last_col`) SELECT `foreign_key_col`,`col_1`,...,`last_col` FROM temp_company;
INSERT INTO contact (`ID`,`col_1`,...,`last_col`) SELECT `foreign_key_col`,`col_1`,...,`last_col` FROM temp_contact;
Just make sure you are selecting the right # of columns.

MySQL Query Update Multiple Tables

I have a contact management system and an sql dump of my contacts with five or six columns of data in it I want to import into three specific tables. Wondering what the best way to go about this is. I have already uploaded the sql dump...its a single table now in in my contact management database.
The tables in the crm require in the companies table only the contactID...and in the songs table:
companyID,
contactID,
date added (not required) and
notes (not required)
Then there is the third table, the contact table which only requires contactname.
I have already uploaded data to each of the three tables (not sure if my order is correct on this) but now need to update and match the data in the fourth table (originally the sql dump) with the other three and update everything with its unique identifier.
Table Structures:
+DUMP_CONTACTS
id <<< I dont need this ID, the IDs given to each row in the CRM are the important ones.
contact_name
company
year
event_name
event_description
====Destination Tables====
+++CONTACTS TABLE++
*contactID < primary key
*contact_name
+++COMPANIES TABLE+++
*companyID < primary key
*name
*contact_ID
*year
++++Events++++
*EventID < primary key
*companyID
*contactID
*eventname
*description
There are parts of your post that I still don't understand, so I'm going to give you SQL and then you can run them in a testing environment and we can take it from there and/or go back and start again:
-- Populate CONTACTS_TABLE with contact_name from uploaded dump
INSERT INTO CONTACTS_TABLE (contact_name)
SELECT contact_name FROM DUMP_CONTACTS
-- Populate COMPANIES with information from both CONTACTS_TABLE + dump
INSERT INTO COMPANIES (name, contact_ID, year)
SELECT d.company, c.contactID, d.year
FROM DUMP_CONTACTS AS d
INNER JOIN CONTACTS_TABLE AS c
ON d.contact_name = c.contact_name
-- Populate SONGS_TABLE with info from COMPANIES
INSERT INTO SONGS_TABLE (companyID, contactID)
SELECT cm.companyID, cm.contact_ID
FROM COMPANIES AS cm
-- Populate Events with info from COMPANIES + dump
INSERT INTO Events (companyID, contactID, eventname, description)
SELECT cm.companyID, cm.contact_ID, d.event_name, d.event_description
FROM DUMP_CONTACTS AS d
INNER JOIN COMPANIES AS cm
ON d.company = cm.name
I first populate CONTACTS_TABLE and then, since the contactID is required for records in COMPANIES, insert records from CONTACTS_TABLE joining the dump. SONGS_TABLE takes data directly from COMPANIES, and lastly the Events gets its data by joining COMPANIES and the dump.

How to migrate a recursive table?

Let's say I have a table, category, which has 3 columns, id, parent_id and name.
I have several tables like this, and I want to consolidate them into one. At present, their IDs will clash (not unique across DBs) so I need to re-ID them. If I make id an auto_increment I can copy all the other columns over just fine, but then parent_id won't link up properly anymore. Is there some magical way I can get the parent_id to point to the correct new ID?
Looking for something like
INSERT INTO newtable (parent_id, name) SELECT ???, name FROM oldtable
How about
Generate a new table with a column containing the name of the old table and old id (oldid, oldtablename) along with a new ID
Add a new column 'newparentid'
Update each row's newparentid to be (SELECT newid FROM newtable nt WHERE oldtablename = row.oldtablename and nt.oldid = row.parent_id)
I imagine you could add an old_id column so that you'll still have the original id and you can run successive updates to the table to modify all the parent_ids to point to the new auto_inc ids. You would obviously have to kill any foreign keys requirements on the table first and reinstitute them after all the changes were made – Patrick