1

I am using query as follows to get any records that begins with any character, has bunch of 0s and ends with number (1 in this case).

where column like '_%[0]1'

But the issue is it's even returning me d0101 etc. which I don't want. I just want d0001, or r0001. Can I use it to exactly match pattern, not partially using like? Any other options in ms-sql?

3 Answers 3

2

SQL-Server does not really do proper regular expressions but you can generate the search clause you want like this:

where column like '_%1' and column not like '_%[^0]%1'

The second condition will exclude all cases where you have a character other than 0 in the middle of the string.

It will allow strings of all possible lengths, provided they start with an arbitrary character, then have any number of 0s and finish with a 1. All other strings will not satisfy the where clause.

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

Comments

0
create table tst(t varchar(10));

insert into tst values('d0101');
insert into tst values('d0001');
insert into tst values('r0001');

select * from tst where PATINDEX('%00%1', t)>0

or

select * from tst where t like '%00%1'

2 Comments

just check for two consecutive 00 and 1 in end using simple like could help.. just check and let me know
While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context.
-1

You use the _ to say that you don't care what char is there (single char) and then use the rest of the string you want:

DECLARE @ TABLE (val VARCHAR(100))

INSERT INTO @ 
VALUES 
('d0001'),
('f0001'),
('e0005'),
('e0001')


SELECT * 
FROM @ 
WHERE val LIKE '_0001'

This code only really handles your two simple examples. If it is more complex, add it to your post.

2 Comments

the number 1 in the example is value that user passes, so if user passes 289, I'll have to return f0289, so I don't know number of 0s.
Add a set of sample input data and expected output for each to your post thats shows a wide set of examples you would come across.

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.