1

複数のセクションがあり、セクションごとに N 個の質問があるアンケートがあります。各セクションには、10 の質問がページに表示されます。Answersを使用して名前を付けたテーブルに 10 個の質問のセットの結果を保存していfor loopます。また、パイプラインに次のセクションをロードするために、すべての質問に回答したときに実行中のセクションを無効にする基準があります。

テーブル 'Answers' に 10 個の質問を送信すると、トリガーを使用して 'QuestionMaster' マスター テーブル内の質問の総数をカウントし、質問は に保存されAnswersます。2 つが等しい場合、現在のセクション ステータスは false になり、次のセクションが選択されます。

私のトリガーは:

ALTER Trigger [dbo].[GetAnsweredQuestionCount]
On [dbo].[Answers]
After Insert
As
Begin
    Declare @sectionid as int
    Declare @companyid as int 
    Declare @Count_Inserted as int
    Declare @Count_remaining as int
Declare @userid as varchar(50)

Set @sectionid = (Select Top(1) SectionId from inserted)
Set @companyid = (Select Top(1) CompanyId from inserted)

Set @userid= (Select Top(1) UserId from inserted )

Set @Count_inserted = (Select count(id) from inserted where SectionId = @sectionid and companyid = @companyid and userid=@userid)

Set @Count_remaining = (Select count(id) from SectionQuestionMap where SectionId = @sectionid and companyid = @companyid and userid=@userid)

If @Count_inserted = @Count_remaining
    begin
        Update SectionCompanyRateMap Set IsCompleted =1 Where SectionId=@sectionid and CompanyId=@companyid
    end
End

私の問題は、ループを使用してレコードを挿入しているため、トリガーが10回も発生することです。これは望ましくありません。すべての質問が保存されたときに一度だけ実行されるように、最初の 9 回のトリガーをスキップする方法があることを知りたいです。

4

2 に答える 2

2

最初のアプローチ:

ループする代わりに、1 つの挿入クエリで各セクションを完了した後に挿入を実行できます。したがって、トリガーは 1 回だけ実行されます。

2番目のアプローチ(最初が不可能な場合):

フラグを保持する追加のビット列を定義し、トリガーでこれをチェックして、トリガーを使用する必要があるかどうかを判断できます。

NOT FOR REPLICATIONオプションを使用してトリガーを無効にすることは可能ですが、これが役立つとは思えません。したがって、最初/2番目のアプローチで説明したような方法を考えてみます。

于 2013-01-13T14:55:51.160 に答える
0

もう1つのオプションと簡単な例

IF OBJECT_ID('dbo.test10') IS NOT NULL DROP TABLE dbo.test10
CREATE TABLE dbo.test10
 (
  Id int IDENTITY
  )
GO  

CREATE TRIGGER dbo.tr_test10 ON dbo.test10
FOR INSERT
AS
BEGIN
  SELECT 'Catch!' AS ColumnInTrigger
END
GO

SELECT Id AS [Start]
FROM dbo.test10

DECLARE @dsql nvarchar(max),
        @i int = 1
SET @dsql = 'DISABLE TRIGGER dbo.tr_test10 ON dbo.test10'
EXEC sp_executesql @dsql

WHILE (@i != 10)
BEGIN
  IF @i = 9
  BEGIN
    SET @dsql = 'ENABLE TRIGGER dbo.tr_test10 ON dbo.test10'
    EXEC sp_executesql @dsql        
  END

  INSERT dbo.test10
  DEFAULT VALUES

  SET @i += 1
END

SELECT Id AS [End]
FROM dbo.test10

SQLFiddle のデモ

于 2013-01-16T15:37:58.953 に答える