-1
に更新されました。したがって、テーブルの更新トリガを作成しようとしています。トリガーは正常に作成され、問題は発生しません。しかし、テーブルを更新しようとすると、「データベースにはすでに#TempTableという名前のオブジェクトがあります」というエラーが表示されます。トリガが正常に作成されたときに、このエラーが表示されるのはなぜですか?ここで更新トリガは正常に作成されましたが、クエリの結果はエラー
は、一時テーブルを使用してトリガのコードです:
Alter trigger tr_tblPerson_forUpdate
on tblPerson
for Update
as
Begin
Declare @Id int
Declare @OldName nvarchar(20), @NewName nvarchar(20)
Declare @OldEmail nvarchar(20), @NewEmail nvarchar(20)
Declare @OldGenderId int, @NewGenderId int
Declare @OldAge int, @NewAge int
Declare @OldSalary int, @NewSalary int
Declare @OldCity nvarchar(20), @NewCity nvarchar(20)
Declare @Auditstring nvarchar (max)
while(Exists(Select Id from inserted))
Begin
Select * into #TempTable from INSERTED -- Since the logical tables INSERTED & DELETED cannot be
-- modified manually, we have to create a separate temptable
-- ourselves and store everything from INSERTED table in that
-- table and then use that to form a loop
Set @Auditstring = ''
Select Top 1 @Id = Id, @NewName = Name, @NewEmail = Email, -- from the inserted table which contains the new data, we are
@NewGenderId = GenderId, @NewAge = Age, @NewSalary = Salary, -- pulling the new data and assigning it to our new data
@NewCity = City from #TempTable -- holding variables
Select @OldName = Name, @OldEmail = Email, @OldGenderId = GenderId,
@OldAge = Age, @OldSalary = Salary,
@OldCity = City from DELETED where Id = @Id
Set @Auditstring = 'Person with ID = ' + cast(@Id as nvarchar(5)) + 'changed'
if(@[email protected])
Set @Auditstring = 'Name to ' + @NewName + ','
if(@[email protected])
Set @Auditstring = 'Email to ' + @NewEmail + ','
if(@[email protected])
Set @Auditstring = 'Gender to ' + cast(@NewGenderId as nvarchar(5))+ ','
if(@[email protected])
Set @Auditstring = 'Age to ' + cast(@NewAge as nvarchar(5))+ ','
if(@[email protected])
Set @Auditstring = 'Salary to ' + cast(@NewSalary as nvarchar(20)) + ','
if(@[email protected])
Set @Auditstring = 'City to ' + @NewCity + 'on ' + cast(GetDate() as nvarchar(20))
insert into tblAudit values (@Auditstring)
Delete from #TempTable where ID = @Id
End
End
そして、ここではエラーになります更新クエリです:
update tblPerson set Name = 'Ray', Email = '[email protected]', Age = 32, Salary = 3000, City = 'New York'
where ID = 1
1)を上書きするのではなく、蓄積しますが、トリガの構文は、MS SQL Serverのです。どの製品を使用していますか? 2)エラーは実行時エラーであり、コンパイル時エラーではありません。コードは構文的に正しいので、トリガーを追加することができます。実際に実行すると、エラーが発生します。あなたは本当にそのような一時テーブルを使うべきではありません。 – Shadow
そのことについて申し訳ありません。タグを削除します。 – TotalGadha
ここでは多くの障害が発生しています。一時テーブルを使用してループを実行しようとしていますが、ループ内にテーブルを作成しています。そして、あなたのループ条件はそのテーブルをチェックしていませんが、 '挿入 'されているので、無限ループです。すべての 'if'チェーン*が以前の結果を上書きするという事実に加えてください。実際には、このすべてを 'inserted'と' deleted'を結合する単一の 'insert ... select'ステートメントとして書くことができます。 –