Sql-server – Substring without the first n characters

sql serversql-server-2016substringt-sql

I'm developing a SQL Server 2016 stored procedure and I want to get the last characters of a varchar(38) column.

I know there will always be at least 18 characters and I don't know the exact length of the column, because it is variable.

I think I can get the length of the column and do a subtract to use SUBSTRING, but I can't do that because I'm doing this:

set @externalCodes = (
    select Serial, AggregationLevel
      from ExternalCode where ProductionOrderId = @productionOrderId
    for json path

I'm generating a JSON and I don't know how to get the length of each Serial column inside a select.

My question is: how can I get a substring from a string without the first 18 characters without knowing its length?

One solution could be:

SUBSTRING(Serial, 18, 38)

And it always return the substring from 18 to the end of the string even if the string doesn't have a length of 38.

Best Answer

I would use:

RIGHT(RTRIM(Serial),LEN(Serial)-18) 

This gets the length of the field and subtracts 18 from it, leaving you with everything after the 18th character.