【问题标题】:Eliminate last 2 char based on condition根据条件消除最后 2 个字符
【发布时间】:2016-07-30 05:29:09
【问题描述】:

我使用这个条件来比较字符串并消除最后 2 个字符

right(tr.item,2) = '%bx' then left(tr.item,len(tr.item)-2)

但我想要多个条件并消除最后 2 个字符。

我试图执行这个语句

right(tr.item,2) like ('%bx','%cx','%ax') then left(tr.item,len(tr.item)-2)

但是我遇到了一个错误

消息 102,第 15 级,状态 1,第 11 行
',' 附近的语法不正确。

请提出实现这一目标的最佳方法。

【问题讨论】:

    标签: sql-server tsql case conditional-statements


    【解决方案1】:

    我想你想要这个逻辑

    (case when right(tr.item, 2) in ('bx', 'cx', 'ax')
         then left(tr.item, len(tr.item) - 2)
         else tr.item
     end)
    

    如果您使用的是right(),则不需要通配符(ala like)。 SQL 中的条件逻辑是通过case 表达式提供的。

    【讨论】:

    • 你说得对,我删除了通配符,它​​起作用了。谢谢
    【解决方案2】:

    试试这个..你需要一个 OR

      ((right(tr.item,2) like ('%bx'))
       or 
      (right(tr.item,2) like ('%cx'))
      or
     (right(tr.item,2) like ('%ax')))
      then left(tr.item,len(tr.item)-2)
    

    【讨论】:

      【解决方案3】:

      由于您使用的是 RIGHT 函数,我认为您不需要 '%'。所以你可以这样做: 对(tr.item,2) IN ('bx','cx','ax')

      【讨论】:

        猜你喜欢
        • 2016-11-17
        • 2012-05-17
        • 2021-10-04
        • 2020-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多