SQL Server : copy table data with FK Constraint - sql-server

I import data into a SQL Server database from Excel.
The data is inserted into a tmptable which has no primary key defined.
tmptable:
course, trainer, jockey, horse, won, pos, date
I want to copy the data from tmptable into another table mastertable which has a primary key column.
mastertable:
coursefk, trainerfk, jockeyfk, horsefk, won, pos, date.
The columns suffixed 'fk' refer to individual other tables.
My hope is that during the insert into mastertable, the script would take the value of course column from tmptable and refer to the table Courses for the appropriate value to be placed into mastertable. The primary and foreign key relationships between the tables have been created, but I cannot create a script that will achieve what I want.
Can anyone please help.

You can join tmptable with other foreign key tables.
Something like this.
INSERT INTO mastertable(coursefk, trainerfk, jockeyfk, horsefk, won, pos, date)
SELECT mastercourse.coursefk, mastertrainer.trainerfk, masterjockey.jockeyfk, masterhorse.horsefk, won, pos, date
FROM tmptable
LEFT JOIN mastercourse ON mastercourse.course = tmptable.course
LEFT JOIN mastertrainer ON mastertrainer.trainer = tmptable.trainer
LEFT JOIN masterjockey ON masterjockey.jockey = tmptable.jockey
LEFT JOIN masterhorse ON masterhorse.horse = tmptable.horse
Note: Since I do not know structure of other FK tables, Please replace and use appropriate table and column names.

Related

SQL Server Insert If Not Exists - No Primary Key

I have Table A and Table B.
Table A contains data from another source.
Table B contains data that is inserted from Table A along with data from other tables. I have done the initial insert of data from A to B but now what I am trying to do is insert the records that do not exist already in Table B from Table A on a daily basis. Unfortunately, there is no primary key or unique identifier in Table A which is making this difficult.
Table A contains a field called file_name which has values that looks like this:
this_is_a_file_name_01011980.txt
There can be duplicate values in this column (multiple files from the same date).
In Table B I created a column data_date which extracts the date from the table a.file_name field. There is also a load_date field which just uses GETDATE() at the time the data is inserted.
I am thinking I can somehow compare the dates in these tables to decide what needs to be inserted. For example:
If the file date from Table A (would need to extract again) is greater than the load_date of Table B, then insert these records into Table B.
Let me know if any clarification is needed.
You could use exists or except. With the explanation here it seems like except would make short work of this. Something like this.
insert tableB
select * from tableA
except
select * from tableB

Merging SQLite3 tables with identical primary keys

I am trying to merge two tables with financial information about the same list of stocks: the first is the prices table (containing, daily, weekly, monthly, etc... price data) and the second is the ratios table (containing valuation and other ratios). Both tables have identical primary key numerical ID columns (referencing the same stock tickers). After creating a connection cursor cur, My code for doing this is:
CREATE TABLE IF NOT EXISTS prices_n_ratios AS SELECT * FROM
(SELECT * FROM prices INNER JOIN ratios ON prices.id = ratios.id);
DROP TABLE prices;
DROP TABLE ratios;
This works fine except that the new prices_n_ratios table contains an extra column named ID:1 whose name is causing problems during further processing.
How do I avoid the creation of this column, maybe by somehow excluding the second tables's first primary key ID column from * (listing all the column names is not an option), or if I can't, how can I get rid of this extra column from the generated table as I have found it very hard to delete it in SQLite3?
Just list all the columns you actually want in the SELECT clause, instead of using *.
Alternatively, join with the USING clause, which automatically removes the duplicate column:
SELECT * FROM prices JOIN ratios USING (id)

How to get the matching records from SQL Server which are not connected by foreign key

I have 2 dimension tables DimLegalEntity and DimMember. They are not connected with any foreign key. Both the tables has "name" column which contains name of the institution. I would like to get the result which contains matching name column from both the tables.
PS. Some data may contain abbreviation in DimLegalEntity.
you can inner join both the table , for join u dont need primary foreign key relationship , as long as column value involved in join condition can be converted to one data type

Error when link 2 table in sql server

I am trying to link 2 table in sql server let's assume one of them called customer and the other is product.
customer has custID as primary key and i want to link it with custID in product table as foreign key, and its give me this error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_product_customer". The conflict occurred in database "xyz", table "dbo.customer", column 'custID #'.
Is there anyone know, how can I fix the issue?
This could have many reasons.
Do you have a type missmatch between those columns?
Is every customer in products also in your customer table?
You can check the second part by using this:
SELECT DISTINCT p.customer_id
FROM products as p
LEFT JOIN customers as c ON p.customer_id = c.customer_id
WHERE c.customer_id is null
Hope this give you a hint.

Updating foreign keys in SQLServer like Access

I have a table, Contacts, with a primary key of ContactID, which is an identity column. I have another table, Person, with a primary key of PersonID that is a foreign key to ContactID. When I insert a record into Person, I would like PersonID to pull the corresponding identity from ContactID in Contact.
In Access, I simply make a query that references both tables, and it will fill in the foreign key column with the corresponding value in the identity (autonumber) column.
SELECT Person.PersonID, Person.FirstName, Person.MiddleName, Person.LastName, Contact.ContactID, Contact.EmailAddress, Contact.PhoneNumber
FROM (Contact INNER JOIN Person ON Contact.ContactID = Person.PersonID);
How can we achieve this in SQLServer 2008 R2? I have been programming triggers to update the keys, but it seems like there ought to be a better way.
Thank you very much for your assistance.
When you insert to the first table, you use the OUTPUT clause to pull the identity value and then you can use it to insert to the child table.
You can also use scope_identity() to do the same thing, but OUTPUT is the preferred method. Do not under any circumstances use ##Identity as it often will give incorrect results and mess up your data integrity.
Look up how to use them in Books Online.

Resources