例:列1
--------------
B978_722
A9786_721
C80516_6
我想取_后面的字符,将转成int型结果如下:列1
--------------
722
721
6请问这条语句如何写,谢谢。

解决方案 »

  1.   

    select right(列1,len(列1)-charindex('_',列1))
    from tb
      

  2.   

    select cast(right(列1,charindex('-',列1)-1) as int) from tb
      

  3.   

    select cast(right(列1,charindex('-',reverse(列1))-1) as int) from tb
      

  4.   

    if not object_id('tb') is null
    drop table tb
    Go
    Create table tb([列1] nvarchar(9))
    Insert tb
    select N'B978_722' union all
    select N'A9786_721' union all
    select N'C80516_6'
    Go
    select 列1=right(列1,len(列1)-charindex('_',列1))
    from tb
    /*
    列1
    ---------
    722
    721
    6*/
      

  5.   


    select convert(int, substring('B978_722',charindex('_','B978_722')+1,len('B978_722')))-------- 
    722
      

  6.   


    这个语句当列中的字符为Asss_050时,会出现转换错误,谢谢了。
      

  7.   

    if not object_id('tb') is null
    drop table tb
    Go
    Create table tb([列1] nvarchar(9))
    Insert tb
    select N'B978_722' union all
    select N'A9786_721' union all
    select N'C80516_6' union all
    select N'Asss_050'
    Go
    select 列1=cast(right(列1,len(列1)-charindex('_',列1))as int)
    from tb
    /*
    列1
    -----------
    722
    721
    6
    50(4 個資料列受到影響)
    */
      

  8.   

    select 
    cast(right(col1,charindex('_',reverse(col1))-1) as int)
    from 
    (values('B978_722'),
    ('A9786_721'),
    ('C80516_6'),
    ('Asss_050')
    )
    tb(col1)
    -----------
    722
    721
    6
    50(4 行受影响)
      

  9.   


    SELECT STUFF(col1,1,CHARINDEX('_',col1),'')
    FROM ...貌似这种写法需要使用函数的次数和引用字段的次数都最少。
    有时SUBSTRING不方便的地方,用STUFF恰恰好。