views:

33

answers:

1

Hi, I have two tables: Department(Dept_ID,Dept_Name). and table Employee(Empl_ID, Empl_Name,Salary,Dept_ID). The IDs are auto-numbers. Dept_ID in table Employee is a foreign key refering to Dept_ID in Table Department. Now, I want to insert a record to table Employee using Excel VBA which is connected to Access 2003 database where my tables reside. How can I get the right value of Dept_ID and insert it to table Employee given that the user will only submit the Dept_Name that belongs to the submitted employee ? I use a simple insert Append query :

insert into table Employee (Empl_Name,Salary,Dept_ID)
values (Parameter_Empl_Name, Parameter_Salary, Parameter_Dept_ID)

I have all the values except the value of Parameter_Dept_ID which referes to the foreign key Dept_ID. I don't know how to generate the correct Dept_ID and insert it to table Employee given that I know the Dept_Name for that ID. Is the problem clear? Please help,

A: 

I would guess that the best bet would be to look up the dept id first, this should allow you to check that it exists and prompt the user if it does not, so, something on the lines of:

Set rs=CreateObject("ADODB.Recordset")

sSQL="SELECT DeptID FROM Depts WHERE DeptName='" & <Cell with Dept Name> & "'"

rs.Open sSQL, <connection>

DeptID=rs!DeptID
Remou
Thanks Remou. I thought of this first, but I thought it might be time consuming. I can easilty do this using SQL server by creating stored procedures. because in SQL server it allows you to write multiple select statements in one query (stored procedure) where I can have the first select statement to do the lookup and the second statement to insert. But I was trying to apply this in MS Access with no success. Are you aware of a way I can use multiple statements in Access Query? example, is there a way to do the following in one query in Access:
guest1
select Parameter_Dept_ID=Dept_ID from Department where Dept_Name="Finance" then in a new line (in the same query) I write: insert into table Employee values ("Mike",2000,Parameter_Dept_ID)
guest1
Remou
Well, but the Select statement contains fields emplo_name and salary which belong to the employee table not the the Depts table. And in the From clause you are using only DeptsTable.
guest1
Your example includes only values, not fields (columns0 selected from another table. If you would like to amend your question to show where the data is coming from, it will be possible to give a fuller answer.
Remou