Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring only if string length > 2

Tags:

substring

sql

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?

like image 369
Rutger Kappers Avatar asked Jun 05 '12 14:06

Rutger Kappers


People also ask

How to extract SUBSTRING from a string?

You can then call the Substring method to extract the substring that you want. The string comparison methods include: IndexOf, which returns the zero-based index of the first occurrence of a character or string in a string instance.

How do you find the specific length of a string?

The idea is to first, get the length L of the string is taken as input and then input the specific character C and initialize empty string str. Now, iterate a loop for L number of times. In every iteration, the specific character is concatenated with string str until the for loop ends.

How do I get the length of a string in SQL query?

SQL Server LEN() Function The LEN() function returns the length of a string. Note: Trailing spaces at the end of the string is not included when calculating the length. However, leading spaces at the start of the string is included when calculating the length.


1 Answers

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
like image 93
Tim Schmelter Avatar answered Sep 22 '22 06:09

Tim Schmelter