I am trying to create a simple to insert trigger that gets the count from a table and adds it to another like this
CREATE TABLE [poll-count](
id VARCHAR(100),
altid BIGINT,
option_order BIGINT,
uip VARCHAR(50),
[uid] VARCHAR(100),
[order] BIGINT
PRIMARY KEY NONCLUSTERED([order]),
FOREIGN KEY ([order]) references ord ([order]
)
GO
CREATE TRIGGER [get-poll-count]
ON [poll-count]
FOR INSERT
AS
BEGIN
DECLARE @count INT
SET @count = (SELECT COUNT (*) FROM [poll-count] WHERE option_order = i.option_order)
UPDATE [poll-options] SET [total] = @count WHERE [order] = i.option_order
END
GO
when i ever i try to run this i get this error:
The multi-part identifier “i.option_order” could not be bound
what is the problem?
thanks
Your trigger currently assumes that there will always be one-row inserts. Have you tried your trigger with anything like this?
Also, you say that SQL Server “cannot access inserted table” – yet your statement says this. Where do you reference
inserted(even if this were a valid subquery structure)?Here is a trigger that properly references
insertedand also properly handles multi-row inserts:However, why do you want to store this data on every row? You can always derive the count at runtime, know that it is perfectly up to date, and avoid the need for a trigger altogether. If it’s about the performance aspect of deriving the count at runtime, a much easier way to implement this write-ahead optimization for about the same maintenance cost during DML is to create an indexed view:
Now the index is maintained for you and you can derive very quick counts for any given (or all)
option_ordervalues. You’ll have test, of course, whether the improvement in query time is worth the increased maintenance (though you are already paying that price with the trigger, except that it can affect many more rows in any given insert, so…).As a final suggestion, don’t use special characters like
-in object names. It just forces you to always wrap it in[square brackets]and that’s no fun for anyone.