I have a table with the following column:
server |
---|
SLQ-ABCD-001 |
SLQ-ABCA-002 |
SLP-DBMSA-003 |
SLD-ABC-004 |
SLS-123456-005 |
I would like to be able to filter the rows based on a substring of this column, specifically, the string between those hyphens; there will always be three characters before the first hyphen and three characters after the second hyphen.
Here's what I have tried:
AND substring(server, 5, (len(server)-8)) in ('ABC', 'DBMSA')
AND substring(server, charindex('-', server)+1,(charindex('-',server, charindex('-', server)+1)-(charindex('-', server)+1))) in ('ABC', 'DBMSA')
Both of these work perfectly fine (expected substrings obtained) when used in the SELECT clause but give the error below
Invalid length parameter passed to the LEFT or SUBSTRING function.
I am not able to use the more simpler way, AND server like '%ABC%' as I have more than one combination of characters I'm looking for and also, because that comma separated list will be dynamically parsed in that query for this use case.
Is there any way this type of filter can be achieved in SQL Server?
EDIT
After @DaleK helped me realize that the issue might be I might have some bad data (server names with length < 8) and that I might have missed them when I tested the expression in the SELECT clause since I might have some other filters in my WHERE clause, here's how I had managed to get around that
SELECT *
from
(SELECT *
from my_original_table
where
--all my other filters that helped me eliminate the bad data
) my_filtered_table
where substring(server, 5, (len(server)-8)) in ('ABC', 'DBMSA');
As for the "question being duplicate" part, I think the error in that question is encountered in SELECT statement where as in my case, the expression worked fine in the SELECT statement and only errored when used in the WHERE clause.
For solution, the one provided by @Isolated seems to work perfectly fine!