Code Snippet for SSMS

在 SQL Server Management Studio (SSMS) 中也可以像 Visual Studio 使用程式碼片段,並可以自訂屬於個人或團隊的程式碼片段。


編輯中加入 Code snippet

在 SSMS Script 編輯區中,按下滑鼠右鍵,出現如下

image

點擊 [Insert Snippet] 或 [Surround With] 會出現搜尋工具,可以滑鼠挑選或輸入關鍵字進行搜尋

image

選擇 Code Snippet 後會在原本編輯區中加入以下的片段

image

這畫面上的變數會有醒目的底色,修改後按下 [Tab] 會移至下一個變數,
全部修改後按下 [Enter] 後原本醒目的底色消失,回到先前編輯得狀態。


Code snippet editor - Snippet Designer

每一個 Code snippet 都是一個附檔名為 .snippet 的 XML 檔案,建議透過 Visual Studio Extension 來編輯。

從 Visual Studio 選單 > [Tools]  > 點擊 [Extensions and Updates],如下圖順序操作,在搜尋框輸入 : Snippet Designer

image


安裝後 Visual Studio 重新啟動,新增檔案時,可以看到  Snippet Designer  下有 Code Snippet 的範本。

image

新增 Code Snippet 檔案前,必須在 Solution 或 專案下才能新增或開啟既有的 *.snippet 檔案。 


編輯主畫面上方是(類似)程式碼,下方是宣告變數

image


在屬性視窗中 [Snippet Type] 會決定這個 Code Snippet 歸類在 [Insert Snippet] 或 [Surround With]

image

選擇 Expansion 會歸類在 [Insert Snippet] ,選擇 SurroundsWith 會歸類在 [Surround With] 。


建議可以參考或複製修改 SSMS 預設的 Code Snippet ,預設儲存的位置在

C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio\SQL\Snippets


自訂 Code snippet

自行修改完成的 Code snippet 儲存於同一個目錄下,
從 SSMS 選單 [Tools] > 點擊 [Code snippets Manager…]

image

點擊 [Add…] ,選擇儲存 Code snippet 檔案的目錄即可。

image


調整 SSMS 顏色

先前有提到 Customize SSMS Setting,若想調整從 code snippet 新加入 Script 中變數的顏色,修改以下兩個項目:

  • Code Snippet Field
  • Code Snippet Field (Selected)

image


筆者選擇 Code Snippet Field 選擇灰色 Gray,Code Snippet Field (Selected) 選擇綠色 Green,效果如下圖

image


參考資源

Getting started with Code Snippets feature of SQL Server 2012 ( article )

Visual Studio Extension - Snippet Designer