Answer the question
In order to leave comments, you need to log in
Creating a trigger in ms sql server 2005
Hi hubr!
Trying to create a trigger in ms sql server 2005
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE Name = 'INSERT_TR_table' AND type = 'TR')
CREATE TRIGGER INSERT_TR_table ON table1
FOR INSERT
AS
DECLARE @temp_row
DECLARE @pkey int
select @pkey = ID from inserted;
SET @temp_row = SELECT top 1 * FROM table1 WHERE ID = @pkey
IF EXISTS (@temp_row)
UPDATE table1 SET
ID = case(inserted.ID) when '' then @temp_row.ID when null then @temp_row.ID else inserted.ID end,
field1 = case(inserted.field1) when '' then @temp_row.field1 when null then @temp_row.field1 else inserted.field1 end,
WHERE ID = @pkey
ELSE
INSERT INTO table1 (ID,field1)
select * from inserted;
GO
Msg 156, Level 15, State 1, Line 38
Incorrect syntax near the keyword 'TRIGGER'.
Msg 156, Level 15, State 1, Line 45
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 47
Incorrect syntax near '@temp_row'.
Msg 137, Level 15, State 2, Line 49
Must declare the scalar variable "@temp_row".
Answer the question
In order to leave comments, you need to log in
Something like this:
UPDATE table1 SET
field1 = CASE WHEN ISNULL(i.field1,'')='' THEN t.field1 ELSE i.field1 END
FROM table1 t INNER JOIN inserted i on t.ID=i.ID
INSERT INTO table1 (ID,field1)
SELECT ID,field1 FROM inserted i WHERE NOT EXISTS (SELECT TOP 1 ID FROM table1 t WHERE t.id = i.id)
In a good way @temp_row
- not needed inserted
- this is a temporary table of inserted records that are placed before calling the trigger code. So treat it like a table (better) or run the cursor over it and do something for each entry (worse).
Well also create trigger
should go the first in a pack, such rules in MSSQL. So first check if there is a trigger and delete it, then go
and then create the trigger.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question