ExeStringtoOriginalSql

作用:

将SQL Server Profiler生成的exec...形式的语句转换为原生版Sql语句,方便分析、格式化语句。实现代码如下:

private string getOriginalSql(string inputString)
        {
            string[] spChart = { "@p0=" };
            string[] stringList = inputString.Split(spChart, StringSplitOptions.RemoveEmptyEntries);

            if (stringList.Length < 2)
            {
                return string.Empty;
            }
            int beginIndex = stringList[0].IndexOf("'");
            string sqlAll = stringList[0].Substring(beginIndex, stringList[0].Length - 2 - beginIndex);
            string[] spChart1 = { ",N'" };
            string[] sqlTemp = sqlAll.Split(spChart1, StringSplitOptions.RemoveEmptyEntries);
            string sql = sqlTemp[0].Substring(1, sqlTemp[0].Length - 2);

            stringList[1] = string.Join("", spChart) + stringList[1];
            string[] tempParValueList = stringList[1].Split(',');

            for (int i = tempParValueList.Length - 1; i >= 0; i--)
            {
                var ps = tempParValueList[i].Split('=')[1];
                if (ps[0] == 'N')
                {
                    ps = ps.Substring(1);
                }
                sql = sql.Replace("@p" + i, ps);
            }
            return sql.Replace("''", "'");
        }

调用语句:

string t1 = this.richTextBox1.Text;
string sql = getOriginalSql(t1);
this.richTextBox2.Text = sql;

 

posted @ 2021-01-19 16:52  Shapley  阅读(131)  评论(0编辑  收藏  举报