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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With