Regular Expression to Match Common SQL Syntax

Regular expression to match common SQL syntax?

Regular expressions can match languages only a finite state automaton can parse, which is very limited, whereas SQL is a syntax. It can be demonstrated you can't validate SQL with a regex. So, you can stop trying.

Regular expression to match Order by sql syntax

I fixed a few things:

order\s+by\s+\w+(\s+asc|\s+desc)?([\s,]*\w+(\s+asc|\s+desc)?)*$

Regular expression for an SQL query

While RegEx is not supported in SQL Server you may try using the pattern matching feature of the LIKE keyword.

Pattern matching in search conditions

SELECT * FROM data WHERE url LIKE '%[a-z]'

Regular expression to match a string in sql

You cannot use CONCAT or alike with REGEX, it will fail. Easiest way to do it, is:

$query = 'SELECT * FROM Test WHERE colb REGEXP "^'.substr($mystring,0,3).'"');

Another is:

SELECT * FROM Test WHERE LEFT(colb, 3) LIKE "{$mystring}%"

Validate SQL Query with Regular Expression

You may add a positive lookahead which checks for the presence of SELECT ... FROM:

^(?=.*SELECT.*FROM)(?!.*(?:CREATE|DROP|UPDATE|INSERT|ALTER|DELETE|ATTACH|DETACH)).*$

While this answers your question, I am worried, because you tagged your question with C#, implying that you are needing to do this from your C# application. In general, you should not ever allow raw SQL code coming in from the outside to execute in your C# code. Instead, always use a prepared statement, where user inputs can be safely sterilized before they run in a query.

If you want a case insensitive match, then use the RegexOptions.IgnoreCase flag when creating your regex:

Regex rgx = new Regex(@"^your pattern$", RegexOptions.IgnoreCase);

Regular Expression to Match All Comments in a T-SQL Script

This should work:

(--.*)|(((/\*)+?[\w\W]+?(\*/)+))

Using 'LIKE' and 'REGEXP' in a SQL query

You do not need to interact with managed code, as you can use LIKE:

SELECT DISTINCT Loggers
FROM [alo].[Forests] C
WHERE (R.LogSU = 3)
AND ForestID LIKE '106[0-9][3-4]')

to make clear: SQL Server doesn't supports regular expressions without managed code. Depending on the situation, the LIKE operator can be an option, but it lacks the flexibility that regular expressions provides.

If you would like to have full regular expression functionality, try this.

Regex to determine legal SQL?

SQL is not a regular language. Use a real validator, such as Mimer.

See also:

  • Is SQL or even TSQL Turing Complete?
  • Regular expression to match common SQL syntax?


Related Topics



Leave a reply



Submit