4

我正在尝试创建一个“而不是插入触发器”,它不会让名称“约翰”将任何内容插入表中。我的问题是,即使我将名称更改为其他名称,查询也会成功,但未添加值。

任何帮助将不胜感激,在此先感谢。

CREATE TRIGGER InsteadOfTrigger
ON Question4
INSTEAD OF INSERT
AS  
Declare @name varchar(50)
Declare @question varchar(50)
Declare @Answer char
Set @name = 'John'
IF (select Username from inserted) = @name
BEGIN
RAISERROR ('You have not paid up your fee', 10,1)
ROLLBACK TRANSACTION
END
ELSE
BEGIN
INSERT INTO question4
values (@name, @question, @Answer)
END
4

2 回答 2

4

好的,所以我已经删除了您的BEGIN语句END之间的and 语句IF ELSE,并将触发逻辑包装在一个BEGIN END

如以下评论中所述,您不需要ROLLBACK TRANSACTION

此外,您还需要填充 @question 和 @Answer 以使它们有任何用途。

CREATE TRIGGER InsteadOfTrigger
ON Question4
INSTEAD OF INSERT
AS 
BEGIN

Declare @name varchar(50)
Declare @question varchar(50)
Declare @Answer char

Set @name = 'John'

IF (select Username from inserted) = @name
    RAISERROR ('You have not paid up your fee', 10,1)
    --ROLLBACK TRANSACTION
ELSE
    INSERT INTO question4
    values (@name, @question, @Answer)

END
于 2013-09-12T12:24:31.417 回答
2

嗯,我注意到您已经声明,但实际上并未在 else 语句中为变量设置值,这可能导致 SQL 无法插入您期望的内容。奇怪的是,我现在需要在作业中做同样的事情,这是我的解决方案:

CREATE TRIGGER instead_of_insert
ON Question4

INSTEAD OF INSERT AS

Declare @Username varchar(25) 
Declare @Question varchar(6)
Declare @Answer char(1)

Set @Username ='John'

IF (Select UserName from inserted) = @UserName
Begin
RAISERROR ('You have not paid up your fee', 10,1)
End

Else
Begin

Set @Username = (Select UserName from inserted)
Set @Question = (Select Question_ID from inserted)
Set @Answer = (Select Answer from inserted)

Insert into User_Responses 
Values
(@username, @Question, @Answer) 

End
于 2014-09-01T04:57:04.150 回答