PDA

View Full Version : Column as a parameter in a trigger


codefox
12-03-2002, 12:20 PM
Here's a trigger


CREATE TRIGGER tAddNewFeedbackItem
ON cust_feedback
FOR INSERT, UPDATE
AS
IF UPDATE(fd_item_id)
ALTER TABLE prj_cust_feedback ADD <col> INTEGER...


Now, is there a way I could refer to the fd_item_id value in the place of <col>? All I'm trying to do is insert a column in prj_cust_feedback with the same name as the newly entered column value in cust_feedback table.

Thanks.

codefox
12-03-2002, 01:59 PM
CREATE TRIGGER tAddNewFeedbackItem
ON cust_feedback
FOR INSERT
AS
IF UPDATE(fd_item_id)
DECLARE @newItemID CHAR(4)
SELECT @newItemID = (SELECT fd_item_id FROM Inserted)
ALTER TABLE prj_cust_feedback ADD @newItemID INTEGER


What's wrong with this trigger. I get an error saying "Incorrect syntax near @newItemID". Can an alter table statement be used in a trigger?

codefox
12-04-2002, 05:00 AM
Well, I got an answer at last. Here's the code:

CREATE TRIGGER tAddNewFeedbackItem
ON cust_feedback
FOR INSERT
AS
IF UPDATE(fd_item_id)
DECLARE @newItemID NCHAR(4)
DECLARE @SQLStatement NVARCHAR(50)
SELECT @newItemID = fd_item_id FROM Inserted
SET @SQLStatement = 'ALTER TABLE prj_cust_feedback ADD ' + @newItemID + ' INT'
EXEC sp_executesql @SQLStatement

Seems variable names could not be used as column names :P. Actually I posted the question in SQL Sever Forums and got this reply http://www.sqlmag.com/forums//messageview.cfm?catid=13&threadid=10843