Click here to Skip to main content
15,900,906 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i want to check sql query pattern and retrieve number of columns and values from query without run it in SQL Server,Here is a example

SQL
INSERT INTO [dbo].[t]
           ([c1]
           ,[c2]
           ,[c3])
     VALUES
           (123,
           'abc',
           321)

SQL
INSERT INTO [dbo].[t]
           ([c1]
           ,[c2]
           ,[c3])
     VALUES
           (869,
           'dlk',
           893)


out put like
Name of Columns and there values
Posted
Updated 1-Dec-15 19:53pm
v2
Comments
[no name] 2-Dec-15 1:39am    
c1,c2,c3 are the column names in table. Do want it in comma separated?
Jawad Ahmed Tanoli 2-Dec-15 1:46am    
it is just an example there may be number of queries with different table name columns name and values.the result may be number of columns and there values does not matter including comma or not
Sergey Alexandrovich Kryukov 2-Dec-15 1:42am    
Parse a query?! Are you going to develop your own SQL server?
—SA
Jawad Ahmed Tanoli 2-Dec-15 1:50am    
no just want to know weather this process can be done through c# or not.As we all know SQL INSERT QUERY can be written in different ways like EXEC('YOUR QUERY') etc.

1 solution

This can be done with a regular expression, but it might not be the best way if you have many different SQL statements you want to parse.

This solution only works for the insert statement.
C#
private static Regex insertExpr = new Regex(@"INSERT INTO\s*\[\w+\].\[\w+\]\s*\((?<columns>[\S\s]+?)\)\s* VALUES\s*\((?<values>[\S\s]+?)\)", RegexOptions.IgnoreCase);
private static Regex contentExpr = new Regex(@"(\[)?(?<val>[\d\w]+)(\])?", RegexOptions.IgnoreCase);


C#
string input = @"INSERT INTO [dbo].[t]
      ([c1]
      ,[c2]
      ,[c3])
VALUES
      (123,
      'abc',
      321)";

Match m = insertExpr.Match(input);
if (m.Success)
{
    MatchCollection cols = contentExpr.Matches(m.Groups["columns"].Value);
    MatchCollection values = contentExpr.Matches(m.Groups["values"].Value);
    
    if (cols.Count != values.Count)
       throw new Exception("Something fishy is going on.");
    
    for (int i=0; i< cols.Count; i++)
    {
       Debug.WriteLine("{0} = {1}", cols[i].Groups["val"].Value, values[i].Groups["val"].Value);
    }
}

The exact output you can modify to your liking.

The other option is to use a lexer and parser, but that is a bit more complicated to get started with.
MinosseCC: a lexer/parser generator for C#[^]
A New Parser Generator for C#[^]
 
Share this answer
 
Comments
Jawad Ahmed Tanoli 3-Dec-15 1:15am    
Thanks for reply :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900