Easy way to convert exec sp_executesql to a normal query?

后端 未结 10 1277
一整个雨季
一整个雨季 2021-01-31 09:37

When dealing with debugging queries using Profiler and SSMS, its pretty common for me to copy a query from Profiler and test them in SSMS. Because I use parameterized sql, my q

10条回答
  •  攒了一身酷
    2021-01-31 09:57

    I spent a little time and created a small modification of Matt Roberts / Wangzq solutions without DECLAREs section, you can try it on .NET Fiddle or download LINQPad 5 file.

    Input:

    exec sp_executesql N'UPDATE MyTable SET [Field1] = @0, [Field2] = @1',N'@0 nvarchar(max) ,@1 int',@0=N'String',@1=0
    

    Output:

    UPDATE MyTable SET [Field1] = N'String', [Field2] = 0
    

    Code:

    using System;
    using System.Linq;
    using System.Text.RegularExpressions;
    
    public class Program
    {
        public static void Main()
        {
            var sql = @"exec sp_executesql N'UPDATE MyTable SET [Field1] = @0, [Field2] = @1',N'@0 nvarchar(max) ,@1 int',@0=N'String',@1=0";
            Console.WriteLine(ConvertSql(sql));
        }
    
        public static string ConvertSql(string origSql)
        {
            var re = new Regex(@"exec*\s*sp_executesql\s+N'([\s\S]*)',\s*N'(@[\s\S]*?)',\s*([\s\S]*)", RegexOptions.IgnoreCase); // 1: the sql, 2: the declare, 3: the setting
            var match = re.Match(origSql);
            if (match.Success)
            {
                var sql = match.Groups[1].Value.Replace("''", "'");
                //var declare = match.Groups[2].Value;
                var setting = match.Groups[3].Value + ',';
    
                // to deal with comma or single quote in variable values, we can use the variable name to split
                var re2 = new Regex(@"@[^',]*?\s*=");
                var variables = re2.Matches(setting).Cast().Select(m => m.Value).ToArray();
                var values = re2.Split(setting).Where(s=>!string.IsNullOrWhiteSpace(s)).Select(m => m.Trim(',').Trim().Trim(';')).ToArray();
    
                for (int i = variables.Length-1; i>=0; i--)
                {
                    sql = Regex.Replace(sql, "(" + variables[i].Replace("=", "")+")", values[i], RegexOptions.Singleline);
                }
                return sql;     
            }
    
            return @"Unknown sql query format.";
        }
    }
    

提交回复
热议问题