axs*_*rog 4 database sql-server triggers
这是场景 - 我会具体说明。我在 Sql 上有一个名为 [Fulcrum_Xfer] 的“桥接”数据库,我使用此桥接是因为名为 [Fulcrum UAT] 的主数据库对某些字段使用 bigint 数据类型,从而在我的 Access 前端的所有字段中显示“ #Deleted data ” - 这种行为在当前设计中无法更改(bigint 必须保留),因此我的 [Fulcrum_Xfer] 数据库中有准确的表名称和字段名称 - [Fulcrum_Xfer] 中的订单表中的 OrderNO 字段是 int,并且没有主字段钥匙
在“你让我们失望”的威胁下,我明天需要做的事情如下
最初插入或更新数据的表称为 Orders,位于 [Fulcrum_Xfer] 数据库中,结构如下
OrderNo int Unchecked
OrderDate smalldatetime Unchecked
ApplicationTenantLinkId int Unchecked
OrderStatus int Unchecked
Run Code Online (Sandbox Code Playgroud)
FulCrum_Xfer 中从 Orders 接收触发数据的表称为 Orders,它在数据库 Fulcrum UAT 中的结构为
OrderNo bigint Unchecked Primarykey
OrderDate smalldatetime Unchecked
ApplicationTenantLinkId Bigint Unchecked
OrderStatus int Unchecked
Run Code Online (Sandbox Code Playgroud)
我需要两个触发器语句,在将新记录插入到 [FulCrum_Xfer] 中的订单后,将其插入到 [Fulcrum UAT] 中的订单中
和
当我在 [Fulcrum_Xfer] 中的订单中进行更改时,我需要一个触发器来更新 [Fulcrum UAT] 中的订单中的任何字段
除了 [FulCrum_XFer] 中的数据库触发器之外,我不知道触发器去了哪里,但我被模板语法吓坏了(不认为我需要所有这些),而且我不知道如何为每个任务编写语法
我是一位非常有经验的 VB / VBA 开发人员,曾使用 ADO 在 SQL 上构建和调用存储过程,但从未在 SQL Server 上执行过此类任务 - 请不要把我当傻子 - 但这非常重要在我现在的工作中。
好吧,当然我无法测试它,但我认为这就是编写 INSERT 触发器的方式:
USE [Fulcrum_Xfer]
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER dbo.trOrders_Insert
ON dbo.Orders
AFTER INSERT AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Just INSERT everything from the [inserted] pseudotable into
--the target table
INSERT INTO [Fulcrum UAT].dbo.Orders
(OrderNo, OrderDate, ApplicationTenantLinkId, OrderStatus)
SELECT OrderNo, OrderDate, ApplicationTenantLinkId, OrderStatus
FROM inserted;
END
GO
Run Code Online (Sandbox Code Playgroud)
将其复制并粘贴到 Management Studio 中的查询窗口中并执行它。
这是我执行 UPDATE 触发器的方法。再次强调,未经测试...
USE [Fulcrum_Xfer]
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER dbo.trOrders_Update
ON dbo.Orders
AFTER UPDATE AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Just UPDATE everything matching [inserted] pseudotable
--into the target table
--(NOTE: This assumes that UPDATES will never change the PK/OrderNo)
UPDATE [Fulcrum UAT].dbo.Orders
SET OrderDate = ins.OrderDate,
ApplicationTenantLinkId
= ins.ApplicationTenantLinkId,
OrderStatus = ins.OrderStatus
FROM [Fulcrum UAT].dbo.Orders As tar
JOIN inserted as ins ON tar.OrderNo = ins.OrderNo;
--(also, performance may not be great as the JOIN columns are
-- different datatypes)
END
GO
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13580 次 |
| 最近记录: |