需要帮助,触发无法正常工作

时间:2016-02-12 16:31:39

标签: sql-server triggers

我有一个触发器在满足条件时更新另一个表,但是当它更新它时更新id字段而不是需要更新的正确字段。请查看代码并告诉我发生了什么。

在此代码中,cardinfotable.cardID是已更新的。

USE [database]
GO
/****** Object:  Trigger [dbo].[trgUpdateCard]    Script Date: 2/12/2016 11:05:23 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

ALTER TRIGGER [dbo].[trgUpdateCard] on [dbo].[CardHolderTable] After insert
As
Declare @Counter bigint;
Declare @maxRandomValue bigint = 2000, @minRandomValue bigint = 1000;
begin
Select Cast(((@maxRandomValue + 1) - @minRandomValue) 
    * Rand() + @minRandomValue As bigint) As '@counter'
    update cardinfotable
    Set CardInfoTable.CardNumber = '@Counter' from cardinfotable
    inner join inserted I on I.CardID = CardInfoTable.CardID        
    where I.Visitor = '1'
END

1 个答案:

答案 0 :(得分:0)

这不是填充变量的正确方法:

Select Cast(((@maxRandomValue + 1) - @minRandomValue) 
    * Rand() + @minRandomValue As bigint) As '@counter'

这是正确的方法:

SET @counter =  Cast(((@maxRandomValue + 1) - @minRandomValue) 
    * Rand() + @minRandomValue As bigint)

然后Sean关于将变量放在单引号中的评论是正确的。如果要实际使用变量中的值,则需要删除引号。

此外,您需要将BEGIN语句移至DECLARE语句之前:

ALTER TRIGGER [dbo].[trgUpdateCard] on [dbo].[CardHolderTable] After insert
As
begin

Declare @Counter bigint;
Declare @maxRandomValue bigint = 2000, @minRandomValue bigint = 1000;
...