Sql 为每个插入的行指定特定字符串

Sql 为每个插入的行指定特定字符串,sql,Sql,这是一个假设情况 我正试图找到一种好方法来确保插入我的表mytable的特定列col1中的每个值在值的开头都有一个特定的字符串http:// 例如: 我想将myprofile插入mytable中,因此(在我的检查条件之后…)最终值将是http://myprofile 我想一个好的方法可能是在insert上使用触发器,但我还没有找到任何具体的方法 有什么想法吗 谢谢。您可以尝试这样做作为起点-这是针对SQL Server的(不太了解MySQL,无法为您提供触发代码): ——创建触发器,给它一个有意

这是一个假设情况

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

例如:

我想将
myprofile
插入
mytable
中,因此(在我的检查条件之后…)最终值将是
http://myprofile

我想一个好的方法可能是在insert上使用触发器,但我还没有找到任何具体的方法

有什么想法吗


谢谢。

您可以尝试这样做作为起点-这是针对SQL Server的(不太了解MySQL,无法为您提供触发代码):

——创建触发器,给它一个有意义的名称
创建触发器PrependHttpPrefix
在dbo.YourTableName上——它在一个特定的表上
INSERT、UPDATE之后——它是针对一个或多个特定操作的
作为
开始
--新插入的行存储在“插入的”伪表中。
--它的结构与此触发器所在的表完全相同
--附属于。
--SQL Server的工作方式是,如果插入影响多个
--行,触发器称为*once*,并且“Inserted”包含这些行
--多行-您需要使用“插入”作为多行数据集
--
--您需要将“插入的”行连接到表中(基于
--表的主键);对于新插入的行
--**不要**在“YourColumn”中以“http://”开头,您需要设置
--将该列值添加到固定文本“http:/”以及插入的内容
更新tbl
设置YourColumn='http://'+i.YourColumn
来自dbo.YourTableName tbl
在tbl.PKColumn=i.PKColumn上插入的内部联接i
左侧(i.YourColumn,7)“http://”
结束

也不要忘记更新触发器。(或者使用存储过程管理所有插入/更新,并且在表上没有直接插入/更新权限。)是的,触发器绝对是您的选择。由于这些关系数据库是高度特定于供应商的,我们真的需要了解您使用的具体关系数据库系统-
oracle
sqlserver
postgresql
等等。您好@marc_s,谢谢您的评论(@jarlh)。有一种SQL-SERVER和MYSQL的方法会很好,但如果我必须选择一种,那就是SQL-SERVER。另一种强制INSERT/UPDATE语句以
http://
(我也假设
https://
?)开头字符串的方法是使用
约束。这样你就不必负责处理这件事了。如果语句违反了约束,则该语句将失败。当然,最好将其记录在案。应遵循jarlh的建议,并将其置于插入、更新后的

-- 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