每个插入行的Concat特定字符串

时间:2016-01-21 14:13:10

标签: sql

这是一个假设的案例..

我正在尝试找到一种好的方法,以确保在我的表col1的特定列mytable中插入的每个值在开头都有一个特定的字符串http://值。

示例:

我想将myprofile插入mytable所以(在我的检查条件之后..)最终值为http://myprofile

我想一个好方法可能是在插入时使用触发器,但我没有找到任何具体的东西..

有什么想法吗?

谢谢。

1 个答案:

答案 0 :(得分: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