0
我想制定出創建觸發器的最佳方式,但是我用命令sql server 2008打了一堵磚牆我希望創建一箇中央表,用於存儲所有應該包含的電話號碼(數字)客戶表中的所有客戶號碼。 Numbers有一個子表號numbercustomer,它將一個號碼鏈接到一個或多個客戶。 我的表:Sql觸發器的父子
CREATE TABLE [Campaign].[Number](
[NumberID] [int] IDENTITY(1,1) NOT NULL,
[Number] [varchar](15) NOT NULL,
[LastUpdated] [timestamp] NOT NULL,
CONSTRAINT [Pk_Number] PRIMARY KEY CLUSTERED
(
[NumberID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [Campaign].[NumberCustomer](
[CustomerNumberID] [int] IDENTITY(1,1) NOT NULL,
[NumberID] [int] NOT NULL,
[CustomerID] [int] NOT NULL,
CONSTRAINT [PK_CustomerNumber] PRIMARY KEY CLUSTERED
(
[CustomerNumberID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [Crm].[Customer](
[CustomerID] [int] IDENTITY(30000,1) NOT NULL,
[FirstName] [varchar](255) NULL,
[LastName] [varchar](255) NULL,
[MobileNumber] [varchar](11) NULL,
[LandlineNumber] [varchar](11) NULL,
CONSTRAINT [PK__Customer__8CB286B91CF15040] PRIMARY KEY CLUSTERED
(
[CustomerID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
我想觸發檢查該號碼錶並插入的數目,如果它不存在。觸發器的第二部分shuld然後檢查並插入,如果不存在與客戶的鏈接。 我可以得到數字表來更新與觸發如下bbut但我關於性能。
CREATE TRIGGER [Crm].[Customer_Number_Updated] ON [Crm].[Customer]
AFTER Update, INSERT
NOT FOR REPLICATION AS
SET NoCount On
DECLARE
@AuditTime DATETIME,
@IsDirty BIT
SET @AuditTime = GetDate()
SET @IsDirty = 0
Begin Try
INSERT INTO
[Campaign].[Number]([Number])
select
number
from
(
Select
i.MobileNumber as number
From
inserted i
join
deleted d
on
i.CustomerID = d.CustomerID
and
isnull(i.MobileNumber ,'') <> isnull(d.MobileNumber,'')
UNION
Select
i.LandlineNumber as number
From
inserted i
join
deleted d
on
i.CustomerID = d.CustomerID
and
isnull(i.LandlineNumber ,'') <> isnull(d.LandlineNumber,'')
UNION
Select
i.AlternateContactNumber as number
From
inserted i
join
deleted d
on
i.CustomerID = d.CustomerID
and
isnull(i.AlternateContactNumber ,'') <> isnull(d.AlternateContactNumber,'')
) as nums
WHERE NOT EXISTS
(
SELECT
*
FROM
[Campaign].[Number] cn
WHERE
cn.Number = nums.number
)
End try
Begin Catch
IF ERROR_NUMBER() <> 2627
DECLARE @ErrorMessage NVARCHAR(4000), @ErrorSeverity INT, @ErrorState INT;
SET @ErrorMessage = ERROR_MESSAGE();
SET @ErrorSeverity = ERROR_SEVERITY();
SET @ErrorState = ERROR_STATE();
RAISERROR(@ErrorMessage,@ErrorSeverity,@ErrorState) with log;
End Catch
GO
任何幫助將不勝感激?
羅布
**號有一個鏈接一個數一個或多個客戶子表numbercustomer。**這似乎不可思議。一個號碼將在多個客戶之間共享?你確定這不是相反的方式,例如。一個客戶可以有多個號碼? – wvdz
客戶可以並且確實有一個或多個數字,也許我應該說我們正在嘗試使用這種方式進行報告,並且在這種情況下,它確實有很多很多 –
我是否正確理解您的代碼正常工作,但您只需要尋找optimalization?也許你應該在你的問題中更清楚地表明情況。 – wvdz