In a database that contains many tables, I need to write a SQL script to insert data if it is not exist.
Table currency
| id | Code | lastupdate | rate |
+--------+---------+------------+-----------+
| 1 | USD | 05-11-2012 | 2 |
| 2 | EUR | 05-11-2012 | 3 |
Table client
| id | name | createdate | currencyId|
+--------+---------+------------+-----------+
| 4 | tony | 11-24-2010 | 1 |
| 5 | john | 09-14-2010 | 2 |
Table: account
| id | number | createdate | clientId |
+--------+---------+------------+-----------+
| 7 | 1234 | 12-24-2010 | 4 |
| 8 | 5648 | 12-14-2010 | 5 |
I need to insert to:
currency
(id=3, Code=JPY, lastupdate=today, rate=4
)client
(id=6, name=Joe, createdate=today, currencyId=Currency with Code 'USD'
)account
(id=9, number=0910, createdate=today, clientId=Client with name 'Joe'
)
Problem:
- script must check if row exists or not before inserting new data
- script must allow us to add a foreign key to the new row where this foreign related to a row already found in database (as currencyId in client table)
- script must allow us to add the current datetime to the column in the insert statement (such as
createdate
inclient
table) - script must allow us to add a foreign key to the new row where this foreign related to a row inserted in the same script (such as
clientId
inaccount
table)
Note: I tried the following SQL statement but it solved only the first problem
INSERT INTO Client (id, name, createdate, currencyId)
SELECT 6, 'Joe', '05-11-2012', 1
WHERE not exists (SELECT * FROM Client where id=6);
this query runs without any error but as you can see I wrote createdate
and currencyid
manually, I need to take currency id from a select statement with where clause (I tried to substitute 1 by select statement but query failed).
This is an example about what I need, in my database, I need this script to insert more than 30 rows in more than 10 tables.
any help