Easy way to convert exec sp_executesql to a normal query?

后端 未结 10 1257
一整个雨季
一整个雨季 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

    Conclusion: I note this still gets a little attention so I'll add details here for what my eventual solution was.

    It turns out that nothing beats doing it for yourself. I created a simple console app that parsed my stored procedure and spit out what I wanted. By adding it to the list of external tools, and passing the current filename as an argument, I could use the following to strip out and rearrange what I needed.

    In use, I'd add a new sql file, paste in the sql, save it, then run the external tool. After it completes, the IDE asks me to reload the file. Poof, no more stored procedure.

    I do note that this may not work with every executesql statement, so you'll have to modify if it does not meet your needs.

    class Program
    {
        const string query = "query";
        const string decls = "decls";
        const string sets = "sets";
        static void Main(string[] args)
        {
            try
            {
                var text = File.ReadAllText(args[0]);
                if(string.IsNullOrEmpty(text))
                {
                    Console.WriteLine("File is empty.  Try saving it before using the hillbilly sproc decoder");
                }
                var regex = new Regex(@"exec sp_executesql N'(?<" + query + ">.*)',N'(?<" + decls + ">[^']*)',(?<" + sets + ">.*)", RegexOptions.Singleline);
                var match = regex.Match(text);
    
                if(!match.Success || match.Groups.Count != 4)
                {
                    Console.WriteLine("Didn't capture that one.  Shit.");
                    Console.Read();
                    return;
                }
    
                var sb = new StringBuilder();
                sb.Append("DECLARE ").AppendLine(match.Groups[decls].Value);
                foreach(var set in match.Groups[sets].Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    sb.Append("SET ").AppendLine(set);
                sb.AppendLine(match.Groups[query].Value.Replace("''", "'"));
                File.WriteAllText(args[0], sb.ToString());
            }
            catch(Exception ex)
            {
                Console.WriteLine("S*t blew up, yo");
                Console.WriteLine(ex.ToString());
                Console.WriteLine("Press a key to exit");
                Console.Read();
            }
        }
    }
    

提交回复
热议问题