Most implementations of substring support omitting the length argument, returning the substring from the nth position to the end of the string, but not SQL Server's, last time I checked.
In the year 2023, is there still no such built-in function?
One workaround is passing a large number definitely greater than the greatest possible length, but that's fragile and crude.
EDIT: because substring(s, 3, datalength(s) - 2)
is clunkier, harder to read, and less maintainable than substring(s, 3)
. And no, I don't think it's unreasonable to expect Microsoft to provide.
len()
, by the way, quietly trims the trailing whitespace, which may or may not be the desired behavior.
SQL Server 2025+/Azure SQL Database
The length
argument is optional.
If length is omitted, all characters from the start position to the end of the expression is returned.
Previous versions
The approach in your edit just needs a minor tweak IMO.
There is no need to do
substring(s, 3, datalength(s) - 3)
You can just do
substring(s, 3, datalength(s))
All you need for the third parameter is that it be at least as long as the number of characters to retain.
As datalength
is the length in bytes and there is no case where the number of characters will exceed this it is safe to use.
In SQL Server 2022 you could also do
substring(s, 3, -1 >> 1)
to somewhat concisely allow for string lengths up to 2,147,483,647 characters without calculating any lengths but this definitely loses readability points.