我正在寻求使用 MS SQL 游标或 SQL while 循环的指导,以根据以下标准使用单个表合并(添加、更新和设置非活动)行,从而寻求最终数据集:
表视图(从表中选择 * 实体 = 123 (@ID)
ENTITY ENTITY_TYPE 值 STATUS_TYPE
123 1 1 1
123 1 4 1
123 1 9 1
表视图(从表中选择 * 实体 = 456 (@OverrideID)
实体 ENTITY_TYPE 值 STATUS_TYPE
456 1 1 1
456 1 5 1
最终数据集如下:
实体 类型 值 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
-- 检查并比较每一行
-- IF @OverrideID = @ID (MATCH)
----- 将@ID 设置为非活动保留副本
-- If @OverrideID != @ID (NOT MATCH)
----- 使用@OverrideID (COPY) 插入@ID 数据
----- 将@ID 设置为非活动.
我开始写以下内容并需要帮助。作为参考,@ID = 123 和 @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