TSQL:使用case语句的奇怪行为

时间:2015-09-30 07:19:31

标签: sql-server

我有一个场景,我必须根据Start_Month更新Customer表的Billing_Start_Month列。

我在excel表中给出了Start_Month值以及客户名称。为此,我创建了一个临时表并插入了所有CustomerName和Start_Month值。在excel表单中,Start_Month值还包含一些其他值,例如:(如果Start_Month是任何月份,如1月,2月等,则将Billing_Start_Month列分别更新为1,2,但如果Start_Month值包含1,3,4,5,7之类的值,则我们需要保留这些记录而不更新customer表的Billing_Start_Month列。我们在excel表中只有5条记录,其Start_Month值类似于“1,3,4,5,7”。

现在我使用以下查询更新Customer表的Billing_Start_Month列:

UPDATE Customer
SET Billing_Start_Month = CASE WHEN tmp.StartMonth = 'January' THEN 1
                               WHEN tmp.StartMonth = ‘February’ THEN 2
                          END
FROM #temp tmp
INNER JOIN Customer c
ON tmp.Customer = c.acc_name    

但是在执行此查询时,我收到了Check Constraint失败错误。当我从临时表中删除包含“1,3,4,5,7”的Start_Month值的记录时,上述查询成功执行。

Simillarly,如果我没有从临时表中删除包含“1,3,4,5,7”的Start_Month值的记录,那么我必须在这样的情况下包括另一个,

CASE WHEN tmp.StartMonth = 'January' THEN 1 
     WHEN tmp.StartMonth = ‘February’ THEN 2
     WHEN tmp.StartMonth = ‘1,3,4,5,7’ THEN 1235 –- any random value and not null
END

请帮助我理解案例陈述的这种行为。我假设,当我在案例陈述中不包括案例'1,3,4,5,7'时,这5条记录不在更新声明中考虑。

2 个答案:

答案 0 :(得分:4)

您的UPDATE语句尝试更新所有记录。根据您的描述,听起来有些情况下您的CASE条件都不会产生任何效果,而您没有其他条件。你可以做ELSE Billing_Start_Month来简单地为与案件不匹配的记录产生电流valye。

或者,您可以在更新中添加WHERE,以便仅更新Start_MonthJanuaryFebruary的行。

答案 1 :(得分:4)

您可以尝试使用以下查询。我在CASE语句中添加了Billing_Start_Month条件,如果月份不是1月或2月,则只使用UPDATE Customer SET Billing_Start_Month = CASE WHEN tmp.StartMonth = 'January' THEN 1 WHEN tmp.StartMonth = 'February' THEN 2 ELSE Billing_Start_Month END FROM #temp tmp INNER JOIN Customer c ON tmp.Customer = c.acc_name (换句话说,在这种情况下,它不会更改记录) )。

{{1}}
相关问题