Can I update column value into a trigger when insert event happens?
I am using SQL Server 2008. Can I update a column value in the same table on which an insert trigger happens?
I.e., can I use this code?
CREATE TRIGGER tr_Table1_Insert_Table1name
ON Table1name
FOR INSERT AS
BEGIN
UPDATE @NEW
SET COLUMN = 3;
END
GO
If "No", 开发者_如何学Gohow can make this happen?
If I understand your question correctly, this should do what you want:
CREATE TABLE dbo.Test_Insert_Trigger (
my_id INT NOT NULL,
my_string VARCHAR(20) NULL,
CONSTRAINT PK_Test_Insert_Trigger PRIMARY KEY CLUSTERED (my_id)
)
GO
CREATE TRIGGER dbo.tri_Test_Insert_Trigger
ON Test_Insert_Trigger FOR INSERT
AS
BEGIN
UPDATE T
SET my_string = CAST(I.my_id AS VARCHAR(20))
FROM
INSERTED I
INNER JOIN dbo.Test_Insert_Trigger T ON
T.my_id = I.my_id
END
GO
INSERT INTO dbo.Test_Insert_Trigger (my_id) VALUES (1)
SELECT * FROM dbo.Test_Insert_Trigger
As OMG Ponies points out though, in many cases a DEFAULT
constraint is what you'll really want here.
Yes, you can. There is no problem with your code since an UPDATE
statement won't interfere with the INSERT
you're overriding. You would want something like this:
UPDATE Table
SET Column = 3
WHERE Table.ID IN (SELECT ID FROM inserted)
AND Table.ID NOT IN (SELECT ID FROM deleted);
This is assuming your table has an ID
column.
You Must Use After Insert Trigger For Update Rows.
CREATE TRIGGER tr_Table1_Insert_Table1name ON Table1name
AFTER INSERT
AS BEGIN
UPDATE Table1
SET COLUMN = 3
Where ...
END
GO
精彩评论