How is the substring function used in SQL Server?
In SQL Server, the SUBSTRING function is used to extract a portion of characters from a string. Its syntax is as follows:
Extract a portion of a given expression starting from a specified position and of a specified length.
- An expression is a string of characters from which to extract information.
- The position at which characters are extracted from the expression is defined as the starting point. Positions are counted from 1.
- “length” refers to the number of characters to be extracted.
Here are some examples of the SUBSTRING function:
- Extract a portion of the string:
SELECT SUBSTRING('Hello World', 7, 5);
The outcome is “World”.
- Extracting a portion of a field value:
SELECT SUBSTRING(column_name, 3, 4) FROM table_name;
This will extract 4 characters starting from the third position of the column_name field in the table.
- Extract the last few characters of a field value.
SELECT SUBSTRING(column_name, LEN(column_name) - 2, 3) FROM table_name;
Three characters will be extracted starting from the third-to-last position of the field value.
Please note that the syntax of the SUBSTRING function may vary slightly in different database management systems. The above is a common usage of the SUBSTRING function in SQL Server.