2014-01-11 338 views
1

我有一個名爲Page的表,該表有一個名爲Priority的列。我希望當我在頁表中插入一行時,優先級列取值爲插入行PageIdPageId是我的表主鍵。如何在插入後爲sql server 2008製作觸發器?

我寫這觸發了它:

CREATE TRIGGER PagePriority 
ON [Page] 
AFTER INSERT 
AS 
Begin 
update inserted 
set [Priority]=(select PageId from [Page] where Page.PageId=inserted.PageId) 
End 

但我對set行一些錯誤。

如何做到這一點?

+1

無法更新「僞代碼表」'Inserted' - 你需要更新**自己的表,而不是**! –

+0

@marc_s是的,你說的對,收下。謝謝。 –

回答

1

請嘗試以下(假設pageid是一個int)

CREATE TRIGGER PagePriority 
ON [Page] 
AFTER INSERT 
AS 
Begin 

DECLARE @thePageId integer = 0 
SET @thePageId = (SELECT PageId from inserted) 

update [Page] 
set [Page].Priority = @thePageId where [Page].PageId = @thePageId 

End 
+0

謝謝你的朋友:) –

+0

你的代碼是錯誤的,如果插入多行,將不會產生正確的結果。 SQL Server觸發器是**語句**,而不是基於行。人們應該總是考慮到這一點。 – peterm