using System.Text.RegularExpressions;
private static readonly string[] ValidSQLStatementPattern = new string[] { "SELECT ", "CREATE TEMPORARY ", "DROP TEMPORARY " };
private const string Semicolon = ";";
private static Regex SemicolonRegeEx = new Regex("\'.*?;.*?\'", RegexOptions.Compiled);
public static void Main()
string temp = "DELETE FROM xyz; TRUNCATE TABLE xyz; INSERT INTO XYZ; UPDATE XYZ SET z=1;SELECT * FROM abc where abc like '% ; %';";
Console.WriteLine(IsValidSQL(temp));
private static int CountStringOccurrences(string inputText, string inputPattern)
while ((i = inputText.IndexOf(inputPattern, i, StringComparison.InvariantCultureIgnoreCase)) != -1)
i += inputPattern.Length;
private static bool IsValidSQL(string inputString)
int semicolonCount = CountSemicolons(inputString);
isValid = (CountValidStatements(inputString) == semicolonCount);
private static int CountValidStatements(string inputString)
foreach(string pattern in ValidSQLStatementPattern)
count+= CountStringOccurrences(inputString, pattern);
private static int CountSemicolons(string inputString)
count= CountStringOccurrences(inputString, Semicolon) - SemicolonRegeEx.Matches(inputString).Count;