我以为我可以玩这个游戏,并且为了达到既定目标,可以在SQL Server 2012 SSMS上运行“保存您运行的每个查询”,这似乎可以在我的机器上完成(添加您自己的错误处理/测试/重构)
它基于Andrei的示例项目(已Connect
替换类)。Codeplex上的SSMSAddin2012项目也非常有用。
namespace SSMSAddin
{
using System;
using System.IO;
using System.Windows.Forms;
using EnvDTE;
using EnvDTE80;
using Extensibility;
using Microsoft.SqlServer.Management.UI.VSIntegration;
public class Connect : IDTExtensibility2
{
private DTE2 application;
private CommandEvents executeSqlEvents;
public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
this.application = (DTE2)application;
this.executeSqlEvents = this.application.Events.CommandEvents["{52692960-56BC-4989-B5D3-94C47A513E8D}", 1];
this.executeSqlEvents.BeforeExecute += this.executeSQLEvents_BeforeExecute;
}
private void executeSQLEvents_BeforeExecute(string guid, int id, object customin, object customout, ref bool canceldefault)
{
try
{
Document document = ((DTE2)ServiceCache.ExtensibilityModel).ActiveDocument;
var textDocument = (TextDocument)document.Object("TextDocument");
string queryText = textDocument.Selection.Text;
if(string.IsNullOrEmpty(queryText))
{
EditPoint startPoint = textDocument.StartPoint.CreateEditPoint();
queryText = startPoint.GetText(textDocument.EndPoint);
}
DateTime now = DateTime.Now;
string folderPath = string.Format(@"E:\SSMS Queries\{0}", now.ToString("yyyyMMdd"));
string fileName = now.ToString("HHmmss-FFFFFFF") + ".sql";
Directory.CreateDirectory(folderPath);
string fullPath = Path.Combine(folderPath, fileName);
File.WriteAllText(fullPath, queryText);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
#region Other Interface Methods
public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom) { }
public void OnStartupComplete(ref Array custom) { }
public void OnAddInsUpdate(ref Array custom) { }
public void OnBeginShutdown(ref Array custom) { }
#endregion
}
}