【问题标题】:update a column depending on the value of another column using case使用大小写根据另一列的值更新一列
【发布时间】:2017-03-08 16:06:19
【问题描述】:

我想根据另一列的值更新一列。 像这样的东西:

update mt
set
 case 
  when mt.type = 1  (1=float 2=boolean 3=datetime 4=character)
  then mt.float_value = mt.value
 end

 case 
  when mt.type = 2  (1=float 2=boolean 3=datetime 4=character)
  then mt.boolean_value = mt.value
 end

case 
  when mt.type = 3  (1=float 2=boolean 3=datetime 4=character)
  then mt.datetime_value = mt.value
 end
...
from myTable mt

我想根据 mt.type 列的值更新列 mt.float_value 或 mt.boolean_value 或 mt.datetime_value 或 mt.char_value

if the column mt.type = 1 then update mt.float_value with  mt.value
if the column mt.boolean_value = 2 then update mt.float_value with  mt.value

等等…… 这可能吗?我该如何执行此更新? 感谢您的帮助

【问题讨论】:

  • 当您只填充表的每一行中的许多列中的一个时,您应该询问架构是否合适。例如,如果您想存储键/值对,其中值可以是任何数据类型,那么为每种数据类型使用单独的表可能比使用包含所有可能数据类型的列的单个宽表更有意义。触发器可用于确保给定键不具有各种数据类型的多个值。另外:您的查询缺少where 子句也很奇怪。

标签: sql tsql


【解决方案1】:

您可以将其拆分为三个查询:

update  mt
set     float_value = convert(value, float)
where   type = 1

update  mt
set     bit_value = convert(value, bit)
where   type = 2

update  mt
set     datetime_value = convert(value, datetime)
where   type = 3

【讨论】:

    【解决方案2】:

    您可以尝试这样做,但如果任何值无法转换为它们的目标列类型,它将失败:

    update mt
    set 
     mt.float_value = case 
      when mt.type = 1  then convert(mt.value, float) else mt.float_value
     end,
    
     mt.boolean_value = case 
      when mt.type = 2  then convert(mt.value, bit) else mt.boolean_value
     end,
    
    mt.datetime_value = case 
      when mt.type = 3  then  convert(mt.value, datetime) else mt.datetime_value
     end
    ...
    from myTable mt
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-25
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 2021-09-17
    • 2019-08-20
    相关资源
    最近更新 更多