写过 Oracle 的触发器,写过 MySQL的触发器,SQLServer 的触发器还是头一次写.
Oracle 和 MySQL 触发器里,要得到 新值 旧值,可以用 NEW 和 OLD 两个关键字,但是SQLServer 里却不能这样.
百度了很久,都是一些不经过大脑的转载.
还好,我在帮助文件里查到了 INSERTED 这个关键字.
CREATE TRIGGER CSK_T_GoodSearchKeywords ON CSK_Store_GoodSearchKeywords FOR INSERT, UPDATE AS
BEGIN
DECLARE @CNT INT;
DECLARE @NEW_VALUE VARCHAR(100);
SELECT @NEW_VALUE = Keywords FROM INSERTED;
SELECT
@CNT = COUNT(1)
FROM
CSK_Store_SearchKeywordsRule R
WHERE
LOWER(R.Input) = LOWER(@NEW_VALUE);
IF (@CNT > 0)
BEGIN
RAISERROR ('[ %s ] exists in CSK_Store_SearchKeywordsRule , so can''t add it into CSK_Store_GoodSearchKeywords', 16, 1 , @NEW_VALUE);
ROLLBACK TRANSACTION
END;
END;
上面这个触发器的意思是如果一个值存在于另外一个表中,这个值就不能插入到当前表.在查询分析器里做违反相关规定的操作时,反映是正常的.但是我用 LINQ 在 WinForm 里进行相关操作试验,第一次由这个触发器抛出错误之后,后面所有操作都报同样的错误.比如:
ipod 这个词以经存在于表 CSK_Store_SearchKeywordsRule,我现在把它插入到 CSK_Store_GoodSearchKeywords ,根据这个触发器里的规定,抛出一个错误:
[ ipod ] exists in CSK_Store_SearchKeywordsRule.........
在应用程序里,这个错误被 捕获.
然后,我在向表 CSK_Store_GoodSearchKeywords 里插入另外一个词,比如 asus ,结果还是报
[ ipod ] exists in CSK_Store_SearchKeywordsRule.........
真是搞不懂为什么.下面是应用程序的代码.
CSK_Store_GoodSearchKeywords gw;
IQueryable<CSK_Store_GoodSearchKeywords> query1 = dc.CSK_Store_GoodSearchKeywords.Where(g => g.Keywords.ToLower() == selectedKeywords);
if (query1.Count() > 0) {
gw = query1.First();
} else {
try {
gw = new CSK_Store_GoodSearchKeywords();
gw.Keywords = selectedKeywords;
dc.CSK_Store_GoodSearchKeywords.InsertOnSubmit(gw);
dc.SubmitChanges();
}catch(Exception ex){
MessageBox.Show(ex.Message);
return;
}
}
| < Prev | Next > |
|---|
Last Updated ( Thursday, 03 September 2009 10:22 )



