【发布时间】:2021-05-17 06:16:03
【问题描述】:
我有一个 SQL 作业问题:
触发器的一个实际用途是在单个表中进行验证(也就是说,可以通过使用正在修改的表中的列来执行验证)。创建一个触发器,验证摘要是否正确插入,即摘要实际上是内容的前 12 个字符,后跟“...”。触发器应拒绝没有有效汇总值的插入。通过发出两个插入命令来验证触发器是否正常工作——一个具有正确的摘要,另一个具有不正确的摘要。列出插入后的 Post 表,以显示一个插入被阻止而另一个成功。
所以 Post 表有如下定义:
Create table Post
(
post_id decimal(12) NOT NULL Primary Key
, person_id decimal(12) NOT NULL Foreign Key references Person(person_id)
, content varchar(255) NOT NULL
, created_on date not null
, summary varchar(15) NOT NULL
)
我遇到问题的部分是:
摘要实际上是内容的前 12 个字符后跟“…”
如何验证字符串的前 12 个是字符?
这是我迄今为止尝试过的:
Create Trigger validate_summary
On Post after insert
as
Begin
Declare @inserted_summary varchar(100) = (Select inserted.summary from INSERTED);
Declare @content varchar(32) = (Select inserted.content from INSERTED)
--If the summary is greater than 15 characters, throw an error
If Len(replace(@inserted_summary, ' ', '*')) > 15
Begin
Rollback;
Raiserror('The summary is not within the 15 character limit', 14, 1)
End
Else If substring(@inserted_summary, 1, 12) <> Substring(@content, 1, 12) AND substring(@inserted_summary, 13, 3) <> '...'
Begin
Rollback;
Raiserror('The summary is does not match the first 12 characters of the content and/or followed by "..."', 14, 1)
End
End
Insert into Post (post_id, person_id, content, created_on, summary)
VALUES
(NEXT VALUE FOR Post_seq, 1, 'Who let the dogs out----Woof Woof!!', GETDATE(), 'Who let the')
此插入语句有效,尽管触发器应该已介入并且插入失败,因为末尾没有“...”。我怎样才能得到这个工作?提前致谢
【问题讨论】:
-
1.您的触发器仅处理单行,如果
inserted包含多行,它将失败 2. 如果在表varchar(15)上声明了summary,则您不需要检查长度 3. 使用THROW而不是ROLLBACK在触发器中 -
LEFT()+ "..." = summary - 现在将其转换为实际的 tsql。而且您需要超越这种 RBAR 方法,在这种方法中,您将某些内容存储到变量中,以便以某种方式检查、使用或引用它。高效的 SQL 代码与集合一起工作;这是一种与传统编码截然不同的实现目标的方式。 -
CHECK约束旨在根据某些掩码检查列值,而不是触发器。这个作业没有很好的示范示范,并引发更多错误重新发明轮子。
标签: sql sql-server tsql triggers