这是一个假设的案例..
我正在尝试找到一种好的方法,以确保在我的表col1
的特定列mytable
中插入的每个值在开头都有一个特定的字符串http://
值。
示例:
我想将myprofile
插入mytable
所以(在我的检查条件之后..)最终值为http://myprofile
我想一个好方法可能是在插入时使用触发器,但我没有找到任何具体的东西..
有什么想法吗?
谢谢。
答案 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