0

I am seeking guidance using MS SQL cursor or SQL while loop to merge (add, update, and set inactive) rows using single table based on criteria below resulting in seeking the final dataset:


TABLE VIEW (SELECT * FROM TABLE WHERE ENTITY = 123 (@ID)

ENTITY    ENTITY_TYPE    VALUE     STATUS_TYPE

123    1     1     1
123    1    4     1
123    1     9     1


TABLE VIEW (SELECT * FROM TABLE WHERE ENTITY = 456 (@OverrideID)

ENTITY    ENTITY_TYPE    VALUE    STATUS_TYPE
456     1    1    1
456    1    5    1

Final Data Set below:

ENTITY   TYPE    VALUE    STATUS_TYPE

123     1     1     3
123     1     4     3
123     1     9     3
456     1     1     1
456     1     4     1
456     1     9     1
456     1     1     1
456     1     5    1

-- Check and compare each row
-- IF @OverrideID = @ID (MATCH)
----- Set @ID to inactive keeping copy
-- If @OverrideID != @ID (NOT MATCH)
----- Insert @ID data with @OverrideID (COPY)
----- Set @ID to inactive.

I began writing the following and need help. For reference, @ID = 123 and @OverrideID = 456


DECLARE @ENTITY BIGINT, @ENTITY_TYPE BIGINT, @VALUE BIGINT, @E1 BIGINT, @T1 BIGINT, @V1 BIGINT
DECLARE type_cursor CURSOR LOCAL FAST_FORWARD FOR
SELECT * FROM TypeValue WHERE ENTITY = @ID

SET NOCOUNT OFF
OPEN type_cursor

FETCH NEXT FROM type_cursor INTO @OverrideID, @ID, @ENTITY, @ENTITY_TYPE, @VALUE

WHILE (@@FETCH_STATUS = 0)
    BEGIN

        SELECT @ENTITY, @ENTITY_TYPE, @VALUE

     IF @VALUE IS NOT NULL
        BEGIN
        SELECT @T1 = @ENTITY_TYPE, @V1 = @VALUE
        END
    ELSE
    BEGIN
    UPDATE TypeValue
    SET ENTITY = @OverrideID, ENTITY_TYPE = @T1, VALUE = @V1 WHERE ENTITY = @ID
    END

FETCH NEXT FROM type_cursor INTO @OverrideID, @ID, @ENTITY, @ENTITY_TYPE, @VALUE

END

CLOSE type_cursor 
DEALLOCATE type_cursor 
SET NOCOUNT OFF 
2
  • 2
    In MS SQL I'd seriously start trying to think in result sets instead of using a cursor.
    – Grixxly
    Oct 11, 2012 at 23:05
  • If you're not doing INSERTs how does your table balloon from 3+2 records to 8? Oct 11, 2012 at 23:39

1 Answer 1

1

That final result set looks like

    select entity,entity_type,value,3 status_type
      from [table]
     where entity = @id
 union all
    select @override,entity_type,value,status_type
      from [table]
     where entity = @id
 union all
    select entity,entity_type,value,status_type
      from [table]
     where entity = @override

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.