我的表格中包含book
,startyear
,endyear
和author
等列。
我需要根据以下条件同时更新startyear
和endyear
列,
STARTYEAR = ENDYEAR where STARTYEAR=0 and ENDYEAR != 0
also
ENDYEAR = STARTYEAR where ENDYEAR =0 and STARTYEAR != 0
可以使用
UPDATE Table SET STARTYEAR = ENDYEAR WHERE STARTYEAR=0 AND ENDYEAR<>0;
UPDATE Table SET ENDYEAR = STARTYEAR WHERE ENDYEAR =0 AND STARTYEAR<>0;
如何在一个查询中编写这两个查询?
答案 0 :(得分:3)
update table
set
startYear = case when startyear = 0 and endyear<>0 then endyear else startYear end,
endYear = case when endyear = 0 and startyear <> 0 then startyear else endYear end
where startyear = 0 or endyear = 0;
答案 1 :(得分:3)
另一种方式是:
UPDATE Table
SET STARTYEAR = STARTYEAR + ENDYEAR
, ENDYEAR = STARTYEAR + ENDYEAR
WHERE STARTYEAR = 0 AND ENDYEAR <> 0
OR ENDYEAR = 0 AND STARTYEAR <> 0 ;
但我真的没有看到任何理由这样做。您可以在事务中使用2语句。它甚至可能比任何复杂的单一陈述更有效。
答案 2 :(得分:1)
您可以使用或更新机器人字段,除非您有触发器阻止您在startyear = endyear = 0;
的情况下执行此操作UPDATE Table SET STARTYEAR = STARTYEAR+ ENDYEAR, ENDYEAR = STARTYEAR+ENDYEAR WHERE STARTYEAR=0 OR ENDYEAR=0
答案 3 :(得分:0)
您无法在一个语句中更新多个表,但是,您可以使用事务来确保将两个UPDATE语句视为一个。您也可以批量处理它们以避免往返。
BEGIN TRANSACTION
UPDATE Table SET STARTYEAR = ENDYEAR WHERE STARTYEAR=0 AND ENDYEAR<>0;
UPDATE Table SET ENDYEAR = STARTYEAR WHERE ENDYEAR =0 AND STARTYEAR<>0;
COMMIT
但在您的情况下,您也可以使用this post中的答案。
答案 4 :(得分:0)
这应该有效,
update test
set startyear = (case when startyear = 0 AND endyear <> 0 then endyear else startyear end),
endyear = (case when endyear = 0 AND startyear <> 0 then startyear else endyear end);