MarianneStone wrote:
> The current version of my code works perfectly, *except
for the fact that it doesn't insert > the ID*!
> Can anyone tell me what I'm doing wrong?
The EmployeeID is not inserted because the getMyID query
cannot find the newly inserted record. When using a UUID to
identify the new records ..
<cfquery name="qAddDeptHead" datasource="#db#"
result="result">
INSERT INTO Employee(... , EmpUUID)
VALUES ( ... , '#CreateUUID()#')
</cfquery>
You have to use that _same_ UUID to find the record, _not_
create a new one.
<cfquery name="getMyID" datasource="#db#">
SELECT EmployeeID, EmpUUID
FROM Employee
WHERE Employee.EmpUUID='#UseTheSameUUIDFromTheFirstQuery#'
</cfquery>
As an aside, you could probably do this in two queries not
three. Just drop the second SELECT query and use an INSERT
INTO/SELECT .. FROM Table statement instead. Plus you should also
consider using cfqueryparam for your query parameters. It has many
benefits.
http://livedocs.adobe.com/coldfusion/8/htmldocs/Tags_p-q_18.html#1102474
> Can anyone ... offer another way of doing this?
There are a few options. For ColdFusion 8, you could use the
result attribute. After running the INSERT you can grab the new
EmployeeID by using #yourResult.IDENTITYCOL#
<cfquery name="qAddDeptHead" datasource="#db#"
result="yourResult">
INSERT INTO Employee ( Columns here )
VALUES (... values here ...)
</cfquery>
For earlier versions, you can either use SCOPE_IDENTITY() or
a UUID value - as you are currently doing now.
> I've tried a few different things, including trying to
use SCOPE_IDENTITY(),
> but just kept getting lots of errors.
If you use SCOPE_IDENTITY() turn off the rowcount, or the
query variable "qAddDeptHead" may be undefined when you try and use
it.
<cfquery name="qAddDeptHead" datasource="#db#"
result="yourResult">
SET NOCOUNT ON;
INSERT INTO Employee ( Columns here )
VALUES (... values here ...)
SELECT EmployeeID AS NewEmployeeID
SET NOCOUNT OFF;
</cfquery>
<cfquery name="qNewEmpPosition" datasource="#db#">
INSERT INTO EmployeePositions(EmployeeID, .... )
VALUES ( #qAddDeptHead.NewEmployeeID#, ....)
</cfquery>