我正在尝试实现一个单一的更新语句,它将获得与下面相同的结果。现在我在php中编译它,其中创建了700多个语句。必须以某种方式我可以使用它们的值来更新所有记录,其中id只在一个语句中匹配。
UPDATE `table` SET `val1` = 1, `val2` = 2, `val3` = 3 WHERE `id` = 1;
UPDATE `table` SET `val1` = 4, `val2` = 5, `val3` = 6 WHERE `id` = 2;
UPDATE `table` SET `val1` = 7, `val2` = 8, `val3` = 9 WHERE `id` = 3;
etc...
在微软网站上的这样的东西看起来我正在寻找什么,但看起来它会非常强大
UPDATE dbo.DimEmployee
SET VacationHours =
( CASE
WHEN ((VacationHours - 10.00) < 0) THEN VacationHours + 40
ELSE (VacationHours + 20.00)
END
)
WHERE SalariedFlag = 0;
我需要它更像下面我不确定它是否可行。
UPDATE 'table'
SET val1,val2,val2 =
(CASE
WHEN (id = 1) THEN val1 = 1, val2 = 2, val3 = 3,
WHEN (id = 2) THEN val1 = 4, val2 = 5, val3 = 6,
WHEN (id = 3) THEN val1 = 7, val2 = 8, val3 = 9
ELSE // do nothing
END
)
答案 0 :(得分:1)
您可以设置一个包含应更新的ID和值的表格。
示例:
declare @idsAndValues table (
id int primary key,
val1 int,
val2 int,
val3 int
)
insert into @idsAndValues (id, val1, val2, val3)
select 1, 1, 2, 3
union all
select 2, 4, 5, 6
union all
select 3, 7, 8, 9
然后你的更新声明:
update table
set
val1 = temp.val1,
val2 = temp.val2,
val3 = temp.val3
from table
inner join @idsAndValues temp on table.id = temp.id
但是如果没有临时表,仍然必须要做到这一点,不是吗?
是的,你可以,我发现最容易使用单独的表格。你可以这样做:
update table
set
val1 = temp.val1,
val2 = temp.val2,
val3 = temp.val3
from table
inner join (
select 1 as Id, 1 as val1, 2 as val2, 3 as val3
union all
select 2, 4, 5, 6
union all
select 3, 7, 8, 9
) temp on table.id = temp.Id
我喜欢这样做(临时表或子查询),而不是出于几个原因:
case
方法进行更新时,您通常会看到else
将行值设置回自身。虽然这在技术上还可以,但对我来说感觉有点脏。答案 1 :(得分:0)
试
UPDATE `table` SET `val1` = (`id`-1)*3+1, `val2` = (`id`-1)*3+2, `val3` = (`id`-1)*3+3;