T-Sql
我的觸發器中缺少什麼?
我有一個可以在其中插入視圖名稱的表,並且以下觸發器應確保只能插入系統中真正存在的 vew_names(這就是觸發器包含的所有程式碼):
CREATE TRIGGER check_if_view_exists ON DATABASE FOR [INSERT], [UPDATE] AS BEGIN IF EXISTS(SELECT view_name from MySpecial_views EXCEPT SELECT name from sys.views) RAISERROR ('You can only insert views in that table that really exist!',10, 1) ROLLBACK END -- end if END -- end trigger
但是,在創建觸發器後,我收到以下錯誤:
消息 102,級別 15,狀態 1,過程 check_if_view_exists,第 1 行
$$ Batch Start Line 0 $$‘INSERT’ 附近的語法不正確。 消息 102,級別 15,狀態 1,過程 check_if_view_exists,第 8 行
$$ Batch Start Line 0 $$‘END’ 附近的語法不正確。
缺什麼?我仔細閱讀了 T-SQL 觸發器的語法,但無法弄清楚為什麼我的觸發器是錯誤的。
注意: 據我所知,您無法像目前嘗試那樣創建數據庫觸發器…
話雖如此,您的 2 條錯誤消息*“Incorrect syntax near ‘INSERT’”和“Incorrect syntax near ‘END’”*是由於您使用方括號
[]
並分別缺少開頭BEGIN
。您的程式碼(帶註釋):
--Remove these Square Brackets... CREATE TRIGGER check_if_view_exists ON DATABASE FOR [INSERT], [UPDATE] AS BEGIN IF EXISTS(SELECT view_name from MySpecial_views EXCEPT SELECT name from sys.views) -- You don't END an IF, you END a BEGIN RAISERROR ('You can only insert views in that table that really exist!',10, 1) ROLLBACK END -- end if END -- end trigger
工作範例:
CREATE TABLE dbo.MySpecialViews ( ViewName varchar(10) ); GO -- Table or View, not on the Database -- ...also no [] around INSERT and UPDATE CREATE TRIGGER CheckIfViewExists ON dbo.MySpecialViews FOR INSERT, UPDATE AS BEGIN IF EXISTS (SELECT ViewName FROM MySpecialViews EXCEPT SELECT name FROM sys.views) -- Added a BEGIN for the code after the IF BEGIN RAISERROR('you can only insert views in that table that really exist!', 10, 1) ROLLBACK END END; GO DROP TABLE dbo.MySpecialViews;
希望這可以幫助。