Substring only if string length > 2

2019-05-06 15:07发布

I was wondering if it was possible to only substring if the string length is > 2?

Here is my sample statement:

Select SUBSTRING(ABRESC, 1, 2) + '-' + SUBSTRING(ABRESC, 3, 5) AS ABRESC From TABLE

However, some fields are only 2 chars long so i was wondering if its possible to only substring when its longer than 2 chars?

标签: sql substring
1条回答
可以哭但决不认输i
2楼-- · 2019-05-06 15:27

You could use CASE

Select ABRESC =
    CASE WHEN LEN(ABRESC) > 2 
       THEN SUBSTRING(ABRESC, 1, 2) + '-' + SUBSTRING(ABRESC, 3, 5)
       ELSE  ABRESC END  
From TABLE
查看更多
登录 后发表回答