问题
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
回答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
来源:https://stackoverflow.com/questions/12849883/using-a-cursor-to-update-rows-in-single-table