0

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

RajKP
  • 263
  • 1
  • 3
  • 6
  • Why do you have separate tables with the same structure, only distinguished by table name suffixes? This is a sign of a bad design in many cases. – Gordon Linoff Mar 31 '14 at 12:00
  • Agreed. But actually that is the regional head's business requirement. – RajKP Mar 31 '14 at 13:56
  • . . Managers should be describing business requirements not technical layouts. There are good reasons to split data into multiple tables, but this sounds like a bad reason. – Gordon Linoff Mar 31 '14 at 15:13
  • Anybody have idea on this kind of scenario? – RajKP Jun 17 '14 at 14:38

0 Answers0