I must import lines from a file into database. I must check if foreign key exists. Here a sample of lines I should import :
A 481 11/23/1981 12 77000 DESCRIPTION_1 $5,098
A 482 11/23/1981 15 77000 DESCRIPTION_1 $5,098
A 482 11/23/1981 12 77000 DESCRIPTION_1 $5,098
A 481 11/23/1981 9 77000 DESCRIPTION_1 $5,098
A 481 11/23/1981 12 77000 DESCRIPTION_1 $5,098
A 481 11/23/1981 12 77000 DESCRIPTION_1 $5,098
A 481 11/23/1981 1 77000 DESCRIPTION_1 $5,098
A 481 11/23/1981 1 77000 DESCRIPTION_1 $5,098
A 481 11/23/1981 1 77000 DESCRIPTION_1 $5,098
A 481 11/23/1981 1 77000 DESCRIPTION_1 $5,098
Here the foreign key are 12, 15, 9, 12, 1. I want to check if one of these foreign key. In the sample the foreign key 12 does not exist. The simplest way is to test line by line :
SELECT COUNT(*) From TypeTable WHERE IdType = 12 -- 0
SELECT COUNT(*) From TypeTable WHERE IdType = 15 -- 1
SELECT COUNT(*) From TypeTable WHERE IdType = 9 -- 1
SELECT COUNT(*) From TypeTable WHERE IdType = 12 -- 1
SELECT COUNT(*) From TypeTable WHERE IdType = 1 -- 1
The problem with this method is that there is one query for each different foreign key, and files I should import has thousands lines (and potentially thousands foreign key).
So I want to know if it’s possible to use the “set feature of SQL” to retrieve in one query but I don’t know how to do this…
PS : In the result of my query, I need to know the foreign key does not exist in database
Regards,
Florian
If the data has been loaded into a staging table then you can use this
To do something set based, you need a table with the desired FK values. This could be a temp table on the same connection and populated by scanning the file. The same SQL would work above by changing
myStagingTableto#myFKTable