Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Wednesday 21 February 2024

REGEXP Function in MSSQL

In Microsoft SQL Server (MSSQL), you can use the LIKE operator with the % wildcard to achieve similar functionality to regular expressions. However, MSSQL also has the PATINDEX function that allows for basic pattern matching.


Here's an example using PATINDEX to simulate regular expression matching:


Suppose you have a table named products with a column product_name, and you want to find all products whose names start with "Apple":


SELECT product_name

FROM products

WHERE PATINDEX('Apple%', product_name) = 1;


In this example:

- product_name is the column containing product names.

- The PATINDEX function is used to match product names using a pattern.

- 'Apple%' is the pattern specified. % acts as a wildcard, matching any sequence of characters after "Apple", and 1 specifies that the match should start at the beginning of the string.


This query will return all product names from the products table where the name starts with "Apple".


While MSSQL doesn't have native support for regular expressions like other databases, you can achieve similar functionality using functions like PATINDEX along with wildcard characters.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.