【问题标题】:Check if the first half of string are characters检查字符串的前半部分是否为字符
【发布时间】: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


【解决方案1】:

您确实需要了解基于集合的逻辑,而不是在这里尝试按程序操作。包括使用documentation 来识别在SQL Server 中Inserted 伪表包含多行(或零行)并且您必须能够处理这一事实。幸运的是,在这种情况下它非常简单,只需使用提供的规则检查是否存在摘要不正确的行。 (我只在超过 12 个字符时添加了...,但如果这不是必需的行为,只需将其删除)。

create trigger validate_summary
on Post after insert
as 
begin
    set nocount on;

    -- Check that the summary has been set according to the rules i.e. first 12 chars + '...'
    -- No null check required since neither column allows null
    if exists (
      select 1
      from Inserted I
      where I.Summary <> substring(I.content, 1, 12) + case when len(I.content) > 12 then '...' else '' end
    ) begin
        -- throw is recommended over raiserror in all but a few cases now
        throw 51000, 'Summary does not match 12 chars of content + ...', 1;
    end;
end;

【讨论】:

  • X 指的是什么?
  • 感谢您的澄清。我刚刚接受了你对我上一个问题的回答:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 2019-08-05
  • 2015-03-14
  • 2020-02-06
  • 1970-01-01
  • 2022-06-14
相关资源
最近更新 更多