I've a trigger on the CONTENT table after update. In the table when the MESSAGE column value updated trigger has to insert a new record with CONTENT_ID and MESSAGE into one of the 4 different tables based on the country. Country value will be retrieved from CONTENT_COUNTRY_INFO table based on the CONTENT_ID column value from the CONTENT table. 4 different tables are CONTENT_IN, CONTENT_MY, CONTENT_CN, CONTENT_HK. I am doing in the following way. But somehow few rows are not inserting into regional tables and not updating the MESSAGE column to "Moved".
ALTER TRIGGER CONTENT_MOVE_TRG ON CONTENT
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON
DECLARE @V_CONTENTID INT
DECLARE @V_COUNTRY VARCHAR(10)
DECLARE CONTENTIDS CURSOR LOCAL FOR SELECT TR.CONTENT_ID FROM CONTENT TR INNER JOIN INSERTED I ON TR.CONTENT_ID = I.CONTENT_ID
OPEN CONTENTIDS
FETCH NEXT FROM CONTENTIDS INTO @V_CONTENTID
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @V_COUNTRY = COUNTRY_NAME FROM CONTENT_COUNTRY_INFO WHERE CONTENT_ID = @V_CONTENTID
IF @V_COUNTRY = 'CN' BEGIN
INSERT INTO CONTENT_CN(CONTENT_ID,MESSAGE) SELECT CONTENT_ID, MESSAGE FROM CONTENT WHERE CONTENT_ID = @V_CONTENTID
END
ELSE IF @V_COUNTRY = 'IN' BEGIN
INSERT INTO CONTENT_IN(CONTENT_ID,MESSAGE) SELECT CONTENT_ID, MESSAGE FROM CONTENT WHERE CONTENT_ID = @V_CONTENTID
END
ELSE IF @V_COUNTRY = 'HK' BEGIN
INSERT INTO CONTENT_HK(CONTENT_ID,MESSAGE) SELECT CONTENT_ID, MESSAGE FROM CONTENT WHERE CONTENT_ID = @V_CONTENTID
END
ELSE IF @V_COUNTRY = 'MY' BEGIN
INSERT INTO CONTENT_MY(CONTENT_ID,MESSAGE) SELECT CONTENT_ID, MESSAGE FROM CONTENT WHERE CONTENT_ID = @V_CONTENTID
END
FETCH NEXT FROM CONTENTIDS INTO @V_CONTENTID
END
UPDATE CONTENT SET MESSAGE='Moved' WHERE CONTENT_ID IN (SELECT TR.CONTENT_ID FROM CONTENT TR INNER JOIN INSERTED I ON TR.CONTENT_ID = I.CONTENT_ID)
CLOSE CONTENTIDS
DEALLOCATE CONTENTIDS
END
I am worried of using the cursor that these kind of problems will arise, looking for the dynamic query to move the records into respective regional tables. Any ideas will be helpful!
Thanks,
Raju