Hi,
I'm just creating a stored procedure (in note pad - I still don't know SQL very well) and I was wondering if the @@identity will still return the RowID (primary key) during an update, or is another select needed ?.
Here is what I have in notepad so far (not tested at all - I don't have SQL locally to test it or the connection info to my host here with me). There are two tables (Users,UsersExtended).
Where the line has "[xxxx]" to help you search where I mean. As I say, untested, I'm just trying to get the basic idea down.
Thanks for taking the time !.
I'm just creating a stored procedure (in note pad - I still don't know SQL very well) and I was wondering if the @@identity will still return the RowID (primary key) during an update, or is another select needed ?.
Here is what I have in notepad so far (not tested at all - I don't have SQL locally to test it or the connection info to my host here with me). There are two tables (Users,UsersExtended).
Code:
CREATE PROCEDURE usp_AddOrUpdate
@uFirstName varchar(30),
@uLastName varchar(30),
@uIP varchar(15),
@uDate datetime,
@uReferral varchar(500),
@uUserAgent varchar(500),
@JavascriptBoolean varchar(1)
AS
Declare @uniqueId int
If Exists (Select * From Users WHERE userFirstName = @uFirstName AND userLastName = @uLastName AND userIP = @uIP)
UPDATE Users
SET LastLogDate = @uDate --update the date
WHERE userFirstName = @uFirstName AND userLastName = @uLastName AND userIP = @uIP
@uniqueId = [xxxx]? -- ? somehow set the unique RowID to a variable for checking in the extended table
ELSE
INSERT INTO Users (userFirstName, userLastName, userIP, LogDate)
VALUES (@uFirstName, @uLastName, @uIP, @Date)
-- "@Date" might be better as "GETDATE" ?
-- set the current unique ID to a variable for inserting into the extended table
@uniqueId = @@identity -- @@IDENTITY or SCOPE_IDENTITY() or IDENT_CURRENT ?
--insert anything new to usersextended table and keep the old
If NOT Exists (Select * From UsersExtended WHERE foreignKey = @uniqueId AND userReferral = @uReferral AND userAgent = @uUserAgent AND JavascriptEnabled = @JavascriptBoolean)
INSERT INTO UsersExtended (foreignKey, userReferral, userAgent, JavascriptEnabled)
VALUES (@uniqueId, @uReferral, @uUserAgent, @JavascriptBoolean)
-----------------------------
##Users Table##
RowID (primary key)
userFirstName
userLastName
userIP
LastLogDate
##UsersExtended Table##
RowID (primary key)
foreignKey (FK)
userReferral
userAgent
JavascriptEnabled
execute usp_AddOrUpdate 'Bob','Smith','127.0.0.1','03/10/2011','htp://example.com','Mozilla/5.0 (iPad; U; CPU OS;)','1'
Where the line has "[xxxx]" to help you search where I mean. As I say, untested, I'm just trying to get the basic idea down.
Thanks for taking the time !.