0

I'm trying to come up with a query in which it's going to filter based on a substring. The substring operation is working fine if I use it as a select statement, but not when I try to use it for filtering

-- These are some examples of the data I have
--cust_12
--cust_123
--temp_db
SELECT SUBSTRING(name,8,LEN(name)) AS ClientId, name FROM sys.databases
WHERE SUBSTRING(name,8,LEN(name)) IN ('12, 123');

If I run the query without the where section, the data is parsed correctly, however when using the where I got no results

1
  • With your logic, the string "cust_12" is evaluated as '' - you start at the 8th character. Commented May 15, 2019 at 22:55

2 Answers 2

4

Is this the logic you want?

WHERE SUBSTRING(name, 8, LEN(name)) IN ('12', '123')

But I think I would be more inclined to write this as:

where name like '%[_]12'] or
      name like '%[_]123' 

I just think the intent is clearer.

Sign up to request clarification or add additional context in comments.

Comments

1

Your quotes are wrong:

SELECT SUBSTRING(name,8,LEN(name)) AS ClientId, name FROM sys.databases
WHERE SUBSTRING(name,8,LEN(name)) IN ('12, 123');

should be:

SELECT SUBSTRING(name,8,LEN(name)) AS ClientId, name FROM sys.databases
WHERE SUBSTRING(name,8,LEN(name)) IN ('12', '123');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.