我正在寻求使用MS SQL游标或SQL while循环来根据以下条件使用单个表合并(添加,更新和设置非活动)行,从而导致寻找最终数据集:
表视图(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
表视图(SELECT * FROM TABLE WHERE ENTITY = 456(@OverrideID)
ENTITY ENTITY_TYPE VALUE STATUS_TYPE
456 1 1 1
456 1 5 1
下面的最终数据集:
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
- 检查并比较每一行
- IF @OverrideID = @ID(MATCH)
-----将@ID设置为非活动保持副本
- 如果@OverrideID!= @ID(不匹配)
-----使用@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
答案 0 :(得分:1)
最终结果集看起来像
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