我现在想通过C#读取一个sql脚本做程序的升级,我的脚本在查询分析器里面可以正常执行,但是通过SqlCommand以Text的形式执行就不行了,有的地方说去掉Go,有的说要加 ; ,修改之后可以执行,但是还是不稳定,有的存储过程中的参数会报错。为了找到一个安全的执行方法,不知道大家有没有这方面的研究?

解决方案 »

  1.   

    要自己作个分隔sql代码的函数才行。
    一般用GO 作分隔就可以了。
    直接读取文本里面的sql代码是不行的。
      

  2.   

            /// <summary>
            /// Sql文本转换为批量执行Sql脚本
            /// </summary>
            /// <param name="sr"></param>
            /// <returns></returns>
            static public List<string> SqlText2SqlList(System.IO.StreamReader sr)
            {
                List<string> SqlList = new List<string>();
                string commandText = "";
                string varLine = "";
                while (sr.Peek() > -1)
                {
                    varLine = sr.ReadLine();
                    if (varLine.Length == 0)
                    {
                        continue;
                    }
                    if (varLine != "GO")
                    {
                        commandText += varLine;                    commandText += "\r\n";
                    }
                    else
                    {
                        SqlList.Add(commandText);
                        commandText = "";
                    }
                }
                return SqlList;
            }