Ik zou het in een SP (Stored Procedure) doen. Je kunt dan een transactie starten, inserten, @@Identity ophalen en je trasactie commiten (of roll-backen). Anders bestaat het gevaar dat je de @@Identity krijgt van iemand die een insert net na de jouwe doet... En dat wil je al helemaal niet. De kans is klein, ik weet het, maar hij is er wel!
Ga ik er dus wel van uit dat je MSSQL gebruikt, maar daar ben je niet heel erg duidelijk in...
edit:
Ik ga effe een voorbeeld uit een bestaande DB voor je halen...
SQL:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
| CREATE PROCEDURE [sp_UpdateUser]
@intID as int,
@strName as varchar(25),
@strPass as varchar(25),
@intUTID as int,
@intCUID as int,
@strEmail as varchar(150),
@bActive as bit,
@bNotify as bit,
@bNotifyNew as bit
AS
SET nocount ON
DECLARE @intNEWID as int
BEGIN TRANSACTION
IF @intID>0
BEGIN
IF (Select Count(us_id) from tbl_Users where (us_name=@strName) and (us_id<>@intID))=0
BEGIN
SET @intNEWID = @intID
UPDATE tbl_Users Set
us_Name = @strName,
us_Password = @strPass,
us_ut_id = @intUTID,
us_cu_id = @intCUID,
us_Email = @strEmail,
us_Active = @bActive,
us_EmailNotify = @bNotify,
us_EmailNotifyNew = @bNotifyNew
Where us_ID = @intID
IF @@error <> 0 GOTO _error
END
ELSE SET @intNEWID = -2 --User exists already!
END
ELSE
BEGIN
IF (Select Count(us_id) from tbl_Users where us_name=@strName)=0
BEGIN
INSERT INTO tbl_Users (
us_Name, us_Password, us_ut_id, us_cu_id, us_Email, us_Active, us_EmailNotify, us_EmailNotifyNew
) VALUES (
@strName, @strPass, @intUTID, @intCUID, @strEmail, @bActive, @bNotify, @bNotifyNew
)
IF @@error <> 0 GOTO _error
SET @intNEWID = @@IDENTITY
END
ELSE SET @intNEWID = -2 --User exists already!
END
_exit:
BEGIN
COMMIT TRANSACTION
set nocount off
SELECT @intNEWID AS success
RETURN
END
_error:
BEGIN
ROLLBACK TRANSACTION
set nocount off
SELECT -1 AS success
RETURN
END
GO |
Deze SP insert een user als het ID<=0, Update de user als het ID>0 en geeft het nieuwe ID terug. (-1 = Fout bij uitvoeren SP, -2 = User bestaat al)...
[
Voor 73% gewijzigd door
RobIII op 20-05-2003 11:52
]
There are only two hard problems in distributed systems: 2. Exactly-once delivery 1. Guaranteed order of messages 2. Exactly-once delivery.
Je eigen tweaker.me redirect
Over mij