【问题标题】:Data manipulation using SQL Server Substring so something else使用 SQL Server 子字符串进行数据操作等等
【发布时间】:2018-06-25 00:44:03
【问题描述】:

我有一个这样的表 A:

ID   Col1
----------------------
1    xyz-abcccc
2    xyz-jkasdasd
3    abcds-asks
4    asdasdasda-as

我想得到这样的输出:

    ID   Col1
    -------------
    1    abcccc
    2    jkasdasd
    3    asks
    4    as

我想在破折号- 之前的任何内容被忽略的地方获得输出。

谢谢

【问题讨论】:

    标签: sql-server substring


    【解决方案1】:

    charindex() 将是一个很好的起点。唯一的技巧是在charindex 函数中添加dash 作为故障安全,从而避免引发错误。

    示例

    Select ID
          ,Col1 = substring(Col1,charindex('-',col1+'-')+1,len(Col1))
     from YourTable
    

    退货

    ID  Col1
    1   abcccc
    2   jkasdasd
    3   asks
    4   as
    

    【讨论】:

    【解决方案2】:

    您也可以使用RIGHTCHARINDEX 函数的组合。

    查询

    select [ID],
    case when [Col1] like '%-%' then right([Col1], charindex('-', reverse([Col1]), 1) - 1)
    else [Col1] end as [new_col1]
    from [your_table_name];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2016-12-02
      • 1970-01-01
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多