而不是插入触发器SQL

时间:2013-09-12 12:11:56

标签: sql-server tsql

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

任何帮助将不胜感激,提前谢谢。

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

2 个答案:

答案 0 :(得分:4)

好的,所以我删除了BEGIN声明之间的ENDIF 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

答案 1 :(得分: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