I am looking to search for a particular email (e.g., fname@exmaple.com) in an nvarchar column in SQL Server. It should have been as easy as –
Select * from Discussion where Comments like '%fname@example.com%'
However the above query is not covering one case. If the result set contains a Comment like “Comment from a user with email selfname@example.com”. In this case the above query will return both records containing ‘fname@example.com’ and ‘selfname@example.com’.
I am looking for a sql query where the email address is matched exactly and the rest of text can be anything.
I am trying to search for an email in multiple tables. The column where we are searching for an email could be an xml, nvarchar(max) for comments and nvarchar(50) for just an email. We need to do perform another job on the record set.
Result set: If I am searching for ‘fname@example.com’, the result set should contain the below:
- lorem ipsum fname@exmaple.com
- fname@example.com lorem ipsum
- Lorem ipsum fname@exmaple.com dolor sit amet
The result set should not contain something like:
- selfname@example.com dolor sit amet
- Lorem ipsum selfname@exmaple.com dolor sit amet
Thanks in advance.
Advertisement
Answer
I came up with the below query.
declare @searchText nvarchar(50) = 'fname@example.com' select * from Discussion where Comments = @searchText or ( CHARINDEX(@searchText, Comments) > 0 and SUBSTRING(Comments, CHARINDEX(@searchText, Comments) - 1, 1) in (' ', '<', '>', '"', '''', ',', ';', '=', '(', ')', '*') and SUBSTRING(Comments, CHARINDEX(@searchText, Comments) + LEN(@searchText), 1) in (' ', '<', '>', '"', '''', ',', ';', '=', '(', ')', '*'))
I am looking for either an exact match or otherwise checking the previous and next characters to assess if the match is meeting the criteria.