I am working on triggers using SQL server 2005. I have a trigger for a table which is after update. After declaring the variables, the code is like this.
if @isconfirmed_before = 0 and @isconfirmed_after = 1
begin
if @invite_userid <> ''
begin
select @points = points from dbo.InvitePoint where code = 'USR' and packageid = @packageid
INSERT INTO InviteCount
([userID]
,[joinMerchantID]
,[packageID]
,[points]
,[joinDate])
VALUES
(@invite_userid
,@merchantid
,@packageid
,@points
,getdate())
end
SET @alpha_numeric=''
SELECT @alpha_numeric=@alpha_numeric+CHAR(n) FROM
(
SELECT TOP 8 number AS n FROM master..spt_values
WHERE TYPE='p' and (number between 48 and 57 or number between 65 and 90)
ORDER BY NEWID()
) AS t
update merchant
set reg_code = @alpha_numeric
where merchantid = @merchantid
END
The last part of
update merchant
set reg_code = @alpha_numeric
where merchantid = @merchantid
This reg_code shoule be inserted only once when the row is inserted but it is changing every time there is an update to the table. How do i make it happen. Please help me, Thank you in advance!!
That code is executing every time there is an update, because you have no conditional flow preventing it from executing sometimes. If you want to only execute that given a certain condition, you’ll need to wrap it in an
IFblock.You say: “This reg_code shoule be inserted only once when the row is inserted but it is changing every time there is an update to the table.” Why is that in an
AFTER UPDATEtrigger then? It looks like it should be in anAFTER INSERTtrigger. Unless I am misunderstanding you.