我有一个触发器,可以在创建条目时插入新号码(accno)。
如何检查client_id是否已经存在,如果是,则更新条目。原因是公司和联系人必须具有相同的accno,因此触发器需要在插入之前检查client_id是否存在,如果存在则更新accno字段。
我的插入触发器如下:
create TRIGGER [dbo].[Set_ACCNo1] ON [dbo].[AMGR_Client_Tbl]
after insert
AS
DECLARE @client_Id varchar(750) DECLARE @NewAccNo varchar(750)
BEGIN SET ROWCOUNT 0 SET NOCOUNT ON
IF EXISTS( SELECT * FROM inserted ) BEGIN
DECLARE I CURSOR LOCAL FAST_FORWARD FOR SELECT Client_Id FROM
Inserted; OPEN I FETCH NEXT FROM I INTO @client_Id; WHILE
@@FETCH_STATUS = 0 BEGIN
SELECT @NewAccNo = Convert(VARCHAR(255), Convert(INT, Acc_No) + 1)
FROM Acc_No WHERE ID = 1;
INSERT INTO A_AccNo(Client_id,Contact_Number,A_AccNo) SELECT
Client_Id, 0, @NewAccNo FROM inserted WHERE Client_Id = @client_Id AND
contact_number = 0;
UPDATE Acc_No SET Acc_no = @NewAccNo WHERE ID = 1;
FETCH NEXT FROM I INTO @client_Id; END CLOSE I DEALLOCATE I END END
GO
我的表是:
CREATE TABLE [dbo].[Acc_No](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ACC_Pref] [varchar](10) NULL,
[Acc_No] [int] NULL ) ON [PRIMARY]
如何检查client_ID?