How to create a flag from regular expressions in Microsoft SQL Server?

mrzz3bfm  于 2023-10-15  发布在  SQL Server
关注(0)|答案(1)|浏览(133)

I have a dataset with IDs and a phone number as a string. I need to build a flag to show if the string is in a valid format.

Here's a dummy dataset.

CREATE TABLE Test 
(
    ID int, 
    Cell varchar(11)
) 

INSERT INTO Test (ID, Cell) 
VALUES (1, '07123456789'), 
       (2, '441234567');

For now, a simple flag that indicates it started with a 0, for example, would be a good starting point for me. I've managed to figure out that Cell LIKE '^0%' should make that work, but I can't figure out how to build it into a Boolean flag.

Thanks for any insights.

kxkpmulp

kxkpmulp1#

You use a case expression (or inline-if) for this:

Select case when Cell like '0%' then 1 else 0 end as MyFlag
from...

Select iif(Cell like '0%', 1, 0) as MyFlag
from...

相关问题