sql server而不是触发器插入语句,其中包含插入的变量和值

发布于 2024-10-14 02:59:46 字数 284 浏览 2 评论 0原文

我有一个替代触发器。我有一个变量值。

我想将值插入到其中一列中并使用插入的字段。这就是我想要实现的目标:

declare @someLocalVariable varchar(9)

set @someLocalVariable = dbo.someLocalUDF()

INSERT myTable (field1, field2, field3)
VALUES (@someLocalVariable, (select field2, field3 from inserted))

I have an instead of trigger. I have a value in a variable.

I would like to insert the value into one of the columns and use the fields from inserted. This is what I am trying to accomplish:

declare @someLocalVariable varchar(9)

set @someLocalVariable = dbo.someLocalUDF()

INSERT myTable (field1, field2, field3)
VALUES (@someLocalVariable, (select field2, field3 from inserted))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

〃温暖了心ぐ 2024-10-21 02:59:46
INSERT INTO myTable (
    field1,
    field2,
    field3
) SELECT
    @someLocalVariable,
    field2,
    field3
FROM
    INSERTED

请记住,如果这是由批量插入触发的(即 INSERTED 有多个记录),则所有记录也将被插入到目标表中。

(恕我直言,这正是它应该做的,但由于某种原因,人们通常会忘记这一点。)

编辑

OP忘记说出他的问题的真正含义:生成唯一的主键值。因此,在这种情况下,一种方法是这样的:

CREATE TRIGGER
    dbo.InsteadOfInsertMyTable
    ON MyTable
    INSTEAD OF INSERT
AS
BEGIN
    INSERT INTO myTable (
        primaryKeyField,
        field2,
        field3
    ) SELECT
        dbo.someUniqueValueGeneratorUDF(),
        field2,
        field3
    FROM
        INSERTED
END
GO
INSERT INTO myTable (
    field1,
    field2,
    field3
) SELECT
    @someLocalVariable,
    field2,
    field3
FROM
    INSERTED

Just remember that if this was triggered by a batch insert (i.e. INSERTED has more than one record), all records will also be inserted into the target table.

(Which is exactly what it should do IMHO, but for some reason people usually forget about that.)

Edit

The OP has forgotten to say what his question was really about: generating unique primary key values. So, in that case, one way of doing that would be something like this:

CREATE TRIGGER
    dbo.InsteadOfInsertMyTable
    ON MyTable
    INSTEAD OF INSERT
AS
BEGIN
    INSERT INTO myTable (
        primaryKeyField,
        field2,
        field3
    ) SELECT
        dbo.someUniqueValueGeneratorUDF(),
        field2,
        field3
    FROM
        INSERTED
END
GO
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文