Talbert1209
Talbert1209

Reputation: 175

T-SQL - How to search for nth character in a string

I have a situation where the 6th and 7th character in a string need to equal '73'. I tried using LIKE '%73%' but the problem is sometimes SQL Server will hit on other 73s that could be in the string. Is there a way to search only the 6th and 7th characters in the string?

Thank you all so much for the help!

Upvotes: 4

Views: 14091

Answers (4)

Gordon Linoff
Gordon Linoff

Reputation: 1269633

Using like, you can do:

where col like '_____73%'

Of course, the other solutions suggesting substring() are also very sensible.

Upvotes: 6

Lamak
Lamak

Reputation: 70638

Use SUBSTRING:

SELECT SUBSTRING(YourColumn,6,2) Result
FROM dbo.YourTable;

Which you can use as a filter:

SELECT *
FROM dbo.YourTable
WHERE SUBSTRING(YourColumn,6,2) = '73';

Upvotes: 3

Marek Vitek
Marek Vitek

Reputation: 1633

Use SUBSTRING ( expression ,start , length )

SELECT mycolumn 
FROM mytable
WHERE SUBSTRING ( mycolumn ,6 , 2 ) = '73'

Upvotes: 13

JohnHC
JohnHC

Reputation: 11195

Try this for SQL Server

select *
from MyTable
where CHARINDEX('73', MyString) = 6

This finds where string '73' starts at position 6

Upvotes: 2

Related Questions