If you try to run a CREATE statement in a query (right click on a database in the Server Explorer) you receive this message.

So i wrote a small utility which will do the job for me.

using System;
using System.IO;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace MdfExec
{
    class Program
    {
        static void Main(string[] args)
        {
            string _cnStr;

            if (args.Length == 2)
            {
                _cnStr =
                    "data source=.\\SQLEXPRESS;Integrated Security=SSPI;" +
                    "AttachDBFilename=" + args[1] + ";User Instance=true;";
            }
            else
            {
                OpenFileDialog fd = new OpenFileDialog();
                fd.AddExtension = true;
                fd.DefaultExt = ".mdf";
                fd.ShowDialog();
                _cnStr =
                    "data source=.\\SQLEXPRESS;Integrated Security=SSPI;" +
                    "AttachDBFilename=" + fd.FileName + ";User Instance=true;";
            }

            using (SqlConnection _cn = new SqlConnection(_cnStr))
            {
                using(SqlCommand _cmd = _cn.CreateCommand())
                {
                    using (StreamReader fs = File.OpenText(args[0]))
                    {
                        _cmd.CommandText = fs.ReadToEnd();
                        _cmd.Connection.Open();
                        _cmd.ExecuteNonQuery();
                    }
                }
            }
        }
    }
}

You can now right click on a *.sql file choose “open with …” and select MdfExec.exe to execute the SQL statement.

Since there is no second parameter (but needed to define to which database to connect) a OpenFileDialog will prompt:

Happy coding