2016-01-21 48 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' –

相关问题