2016-01-21 72 views
2

這是一個假設的例子..的毗連特定字符串的每一個插入的行

我試圖找到一個很好的辦法,以確保每一個插在我的表mytable的特定列col1值都有一個特定的字符串http://開頭的值。

例子:

我想插入myprofilemytable左右(經過我的檢查條件..)終值將http://myprofile

我想,一個很好的辦法可以使用插入時的觸發,但我沒有找到具體的東西..

任何想法?

謝謝。

+4

不要忘記更新觸發太。 (或者使用存儲過程管理所有插入/更新,並且無需直接在表上插入/更新權限。) – jarlh

+0

是的,觸發器絕對是您的選擇。由於這些是**高度**供應商特定的,我們真的需要知道你正在使用的具體RDBMS - 'oracle','sql-server','postgresql'等。 –

+0

嗨@mar​​c_s,謝謝你你的評論(@jarlh)。擁有SQL-SERVER和MYSQL的方法會很棒,但如果我必須選擇一個,它將是SQL-SERVER。 –

回答

1

你可以嘗試這樣的事情作爲一個起點 - 這是SQL Server(不知道MySQL的不夠好,爲您提供該觸發代碼):

-- create the trigger, give it a meaningful name 
CREATE TRIGGER PrependHttpPrefix 
ON dbo.YourTableName   -- it's on a specific table 
AFTER INSERT, UPDATE   -- it's for a specific operation, or several 
AS 
BEGIN 
    -- the newly inserted rows are stored in the "Inserted" pseudo table. 
    -- It has the exact same structure as your table that this trigger is 
    -- attached to. 
    -- SQL Server works in such a way that if the INSERT affected multiple 
    -- rows, the trigger is called *once* and "Inserted" contains those 
    -- multiple rows - you need to work with "Inserted" as a multi-row data set 
    -- 
    -- You need to join the "Inserted" rows to your table (based on the 
    -- primary key for the table); for those rows newly inserted that 
    -- **do not** start with "http://" in "YourColumn", you need to set 
    -- that column value to the fixed text "http:/" plus whatever has been inserted 
    UPDATE tbl 
    SET YourColumn = 'http://' + i.YourColumn 
    FROM dbo.YourTableName tbl 
    INNER JOIN Inserted i ON tbl.PKColumn = i.PKColumn 
    WHERE LEFT(i.YourColumn, 7) <> 'http://' 
END 
+0

應該遵循jarlh的建議,並把它放在'AFTER INSERT,UPDATE' –

相關問題