我在我的存储过程中有一个表作为表类型参数接收(它来自excel工作簿源,但这是一个不同的故事)。它有几列我需要根据每列的有效值列表验证值。
让我们说我的表OriginDetails
看起来像这样(请注意,这只是模拟数据;我有两个这样的表,每8列我将验证) -
Origin | Status | Priority | ErrMsg
------------------------------------------
Testing | In Review | Low |
Design | Initiated | Medium |
Prod | Declined | Critical |
而且,我正在针对三个不同的列表验证列Origin
,Status
和Priority
中的值(实际上我正在验证表中数据的值,但为了简单起见,我这里对这些值进行了硬编码),并根据我的验证更新了ErrMsg
列 -
UPDATE OriginDetails
SET ErrMsg = ErrMsg + '|Invalid Origin'
WHERE Origin NOT IN ('Pre-Design','Design','Development')
UPDATE OriginDetails
SET ErrMsg = ErrMsg + '|Unrecognized Status'
WHERE Status NOT IN ('In Review','Approved')
UPDATE OriginDetails
SET ErrMsg = ErrMsg + '|Priority check failed'
WHERE Priority NOT IN ('Critical','Medium','High')
这一切都很好,花花公子,效果很好 - 但我最终得到了16个这样的2个表的更新语句,所以我有一个非常庞大和丑陋的代码块(还有很多重复,因为我几乎完全相同2个表的代码。)
有没有办法可以在每个表的一个语句中实际执行所有更新?
如下所示,除了它应该执行每个条件而不是只有一个 -
UPDATE OriginDetails
SET ErrMsg = ErrMsg +
(CASE WHEN Origin NOT IN ('Pre-Design','Design','Development')
THEN '|Invalid Origin'
WHEN Status NOT IN ('In Review','Approved')
THEN '|Unrecognized Status'
WHEN Priority NOT IN ('Critical','Medium','High')
THEN '|Priority check failed'
END)
任何想法/方向都表示赞赏。感谢。
答案 0 :(得分:6)
这样的事情应该运作良好(并且只需要您输入一次值):
UPDATE OriginDetails
SET ErrMsg = ErrMsg +
CASE WHEN Origin NOT IN ('Pre-Design','Design','Development') THEN '|Invalid Origin' ELSE '' END
+ CASE WHEN Status NOT IN ('In Review','Approved') THEN '|Unrecognized Status' ELSE '' END
+ CASE WHEN Priority NOT IN ('Critical','Medium','High') THEN '|Priority check' ELSE '' END
这是SQL Fiddle。
祝你好运。答案 1 :(得分:1)
这个怎么样:
UPDATE OriginDetails
SET ErrMsg = ErrMsg +
(CASE
WHEN Origin NOT IN ('Pre-Design','Design','Development') and Status NOT IN ('In Review','Approved') and Priority NOT IN ('Critical','Medium','High')
THEN '|Invalid Origin|Unrecognized Status|Priority check failed'
WHEN
Origin NOT IN ('Pre-Design','Design','Development') and Status NOT IN ('In Review','Approved') and Priority IN ('Critical','Medium','High')
THEN '|Invalid Origin|Unrecognized Status'
END)
你可以像我一样添加所有案例。