private void AttachDataBase()
        {
            string Str_mdf;
            string Str_ldf;
            string SqlCommandText;            Str_mdf = "E:\\DataBase\\Test_Data.MDF";
            Str_ldf = "E:\\DataBase\\Test_log.LDF";            SqlCommandText = "EXEC sp_attach_db @dbname = N'" 
                           + "Lisun_Test" + "'," 
                           + "@filename1 = N'" + Str_mdf + "',"
                           + "@filename2 = N'" + Str_ldf + "'";            SqlCommand thisCommand = new SqlCommand();            thisCommand.CommandType = System.Data.CommandType.StoredProcedure;
            thisCommand.Connection  = SQLConn;     //全局SQLConn已经正常打开
            thisCommand.CommandText = SqlCommandText;            thisCommand.ExecuteNonQuery();   //为何执行到这一句话就出错,我把SqlCommandText中的文本拷贝到sqlserver2005中运行正常.

解决方案 »

  1.   

    thisCommand.CommandType = System.Data.CommandType.StoredProcedure;
    改成SQL试试。存储过程不是这么用的。
      

  2.   

    一楼对的!thisCommand.CommandType = System.Data.CommandType.Text;
      

  3.   

    试试这样:
    class Program
    {
        static void Main(string[] args)
        {
            string mdf = @"C:\test.mdf";
            string ldf = @"C:\test_log.ldf";
            string cmd = string.Format("sp_attach_db");
            SqlConnection connection = new SqlConnection("Server=(local); Database=master; Integrated Security=SSPI");
            connection.Open();
            SqlCommand command = new SqlCommand();
            command.Parameters.Add(new SqlParameter("dbname", "Liu"));
            command.Parameters.Add(new SqlParameter("filename1", mdf));
            command.Parameters.Add(new SqlParameter("filename2", ldf));
            command.Connection = connection;
            command.CommandText = cmd;
            command.CommandType = CommandType.StoredProcedure;
            command.ExecuteNonQuery();
        }
    }
      

  4.   

    我上面的代码是通过的,你不要在sql语句中直接写参数,用Parameters.Add就可以通过。
      

  5.   

    因为你用的是EXEC所以要使用TEXT模式,或者你去掉EXEC然后参数使用Parameter的形式
      

  6.   

    SqlCommand thisCommand = new SqlCommand(SqlCommandText ,SQLConn); 
    这样不是更好吗?
    干嘛要多那么多语句?
      

  7.   

    LZ的SqlCommandText 是一个动态的SQL语句吧!不是存储过程 ,所以要改成2楼的样式。1楼说的对,存储过程不是这样用的。