記一次SQL Server Insert觸發器編寫過程


實現功能:新增特定類型的新聞時,自動追加特定的背景圖片。

第一版(錯誤信息:不能在 'inserted' 表和 'deleted' 表中使用 text、ntext 或 image 列),代碼如下:

--創建insert插入類型觸發器
if (object_id('tgr_news_QA_insert', 'tr') is not null)
    drop trigger tgr_news_QA_insert
go

create trigger tgr_news_QA_insert
on news
     for insert --插入觸發
as
    --定義變量
    declare @id bigint, @content nvarchar(max),@newstype bigint;

    --在inserted表中查詢已經插入記錄信息
    select @id = id, 
    @content = [content],
    @newstype = newstype 
    from inserted

    --處理問題解答數據
    if @newstype=101
    begin
        set @content = '<div style="background:url(''images/newsBackgroundImg.jpg'') no-repeat;width:700px;height:600px;  "><div width=''100%'' style=''text-align:left;''>'+@content+'</div></div>'
        update news set content=@content where id=@id
    end

go

於是改成instead of insert觸發器,代碼如下:

--創建insert插入類型觸發器
if (object_id('tgr_news_QA_insert', 'tr') is not null)
    drop trigger tgr_news_QA_insert
go

create trigger tgr_news_QA_insert
on news
     instead of insert --插入觸發
as
    --定義變量
    declare @id bigint, @content nvarchar(max),@newstype bigint;

    --在inserted表中查詢已經插入記錄信息
    select @id = id, 
    @content = [content],
    @newstype = newstype 
    from inserted

    --處理對應類型的數據
    if @newstype=101
    begin
        set @content = '<div style="background:url(''images/newsBackgroundImg.jpg'') no-repeat;width:700px;height:600px;  "><div width=''100%'' style=''text-align:left;''>'+@content+'</div></div>'
        insert into news 
        select id, newstype, title, @content content, 
        from inserted
    end
    else
        insert into news 
        select * from inserted      

以上插入觸發器代碼雖然沒有報錯,也實現了效果,但是存在漏洞。

  1. ntext轉nvarchar(max)是否會有數據丟失
  2. inserted 數據不一定只有一條

最終版:

--創建insert插入類型觸發器
if (object_id('tgr_news_QA_insert', 'tr') is not null)
    drop trigger tgr_news_QA_insert
go

create trigger tgr_news_QA_insert
on news
     instead of insert --插入觸發
as
        insert into news 
        select id, 
            newstype,
            title, 
            '<div style="background:url(''images/newsBackgroundImg.jpg'') no-repeat;width:700px;height:600px;  "><div width=''100%'' style=''text-align:left;''>'+convert(nvarchar(max),content)+'</div></div>', 
        from inserted
        where newstype=101

        insert into news 
        select id, 
            newstype,
            title, 
            [content], 
        from inserted
        where newstype<>101

 

關於SQL Server 2005中NTEXT與NVARCHAR(MAX)參考:http://www.cnblogs.com/dudu/archive/2009/10/17/1585152.html 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM