Let me explain my situation. I have 3 tables generated with
CREATE TABLE Partners
(
id INT IDENTITY(1,1),
name NVARCHAR(50) NOT NULL,
PRIMARY KEY (id)
);
-- snip ...
CREATE TABLE Questions
(
id INT IDENTITY(1,1),
section_id INT,
qtext NVARCHAR(300) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (section_id) REFERENCES Sections(id) ON DELETE CASCADE
);
-- snip ...
CREATE TABLE Answers
(
id INT IDENTITY (1,1),
question_id INT,
partner_id INT,
val DECIMAL DEFAULT 0.0,
PRIMARY KEY (id),
FOREIGN KEY (question_id) REFERENCES Questions(id) ON DELETE CASCADE,
FOREIGN KEY (partner_id) REFERENCES Partners(id) ON DELETE CASCADE
);
and I'm trying to set up a trigger so that when a new partner is added, default answers get for him get generated for every question.
My attempt at creating that trigger is
-- Create trigger so that adding a partner results in default
-- answers for every survey
-- See https://stackoverflow.com/questions/11852782/t-sql-loop-over-query-results
CREATE TRIGGER DefaultAnswers
ON Partners
AFTER INSERT
AS
BEGIN
CREATE TABLE QuestIds (RowNum INT, Id INT);
INSERT INTO QuestIds (RowNum, Id)
SELECT DISTINCT ROW_NUMBER() OVER (ORDER BY Id) as RowNum, Id
FROM TABLE
DECLARE @id INT
DECLARE @totalrows INT = (SELECT COUNT(*) FROM QuestIds)
DECLARE @currentrow INT = 1
WHILE @currentrow < @totalrows
BEGIN
SET @id = (SELECT Id FROM QuestIds WHERE RowNum = @currentrow)
EXEC AddAnswerWithoutVal @question_id=@id, @partner_id=INSERTED.id
SET @currentrow = @currentrow +1
END
END
and the errors are
Msg 156, Level 15, State 1, Procedure DefaultAnswers, Line 313
Incorrect syntax near the keyword 'TABLE'.Msg 102, Level 15, State 1, Procedure DefaultAnswers, Line 323
Incorrect syntax near '.'.
Can you help me figure out the problem? INSERTED
, I thought, refers to the row that was just inserted in the table. As for the FROM TABLE
, that too was something I tried to rip off of T-SQL loop over query results.
EDIT: I have another question. When I get this working, will the trigger refer to a row that was successfully inserted? I want to make sure this is an atomic operation.