268 字
1 分鐘
Always Adding Comments When Writing SQL in SSMS? Generate with Code Snippet in One Click
Conclusion
- Use SSMS Code Snippet to create a comment template; typing
cmtwill quickly generate a complete SQL comment structure.
Where It’s Useful
- Teams need to standardize SQL comment formats
- Frequently write Stored Procedures / Scripts
- Want to reduce time spent repeatedly pasting templates
- Want to improve SQL readability and maintainability
Process Steps
1. Create the Snippet File
- Save the XML as a
.snippetfile and place it in the specified path - Path:
C:\Users\@User\Documents\SQL Server Management Studio 21\Code Snippets\SQL\My Code Snippets- SSMS will automatically read snippets in this folder (requires SSMS restart to take effect)
2. Configure the Snippet Structure
- Define the title, shortcut (Shortcut), and variables (Literal)
- Set the Shortcut to
cmt; then, typing cmt + Tab will expand it directly - Variables like
$author$and$date$allow for quick value filling
<CodeSnippets xmlns="<http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet>"> <CodeSnippet Format="1.0.0"> <Header> <Title>SQL-Comment</Title> <Shortcut>cmt</Shortcut> <Description>SQL-Comment</Description> <Author>J</Author> </Header>
<Snippet> <Code Language="SQL"><![CDATA[-- =============================================-- Author: $author$-- Create Date: $date$-- Description: $desc$-- =============================================/* Parameter: $param$
SQL: $sql$
Log: $log$*/]]></Code>
<Declarations> <Literal> <ID>author</ID> <Default>YourName</Default> </Literal>
<Literal> <ID>date</ID> <Default>yyyy/MM/dd</Default> </Literal>
<Literal> <ID>desc</ID> <Default>Description</Default> </Literal>
<Literal> <ID>param</ID> <Default>@Param Comment</Default> </Literal>
<Literal> <ID>sql</ID> <Default>SQL Sample</Default> </Literal>
<Literal> <ID>log</ID> <Default>yyyyMMdd by YourName - adjustment notes</Default> </Literal> </Declarations> </Snippet> </CodeSnippet></CodeSnippets>3. Use the Snippet
- In the SSMS Query window, type:
cmt- Press
Tab→ The template will expand automatically - Then use
Tabto switch between fields and fill in values
Additional Notes
- SSMS does not reload Snippets in real-time → A restart is required
- If there’s a Shortcut conflict, it won’t expand (recommend using a short but uncommon name)
- You can create multiple snippets (e.g., sp, select, log templates)
Commands / Examples Summary
Click to expend
- Expand snippet:
cmt + TabWrap-up
- Laziness isn’t the problem; repetitive writing is. Snippets help you reclaim your time.
Always Adding Comments When Writing SQL in SSMS? Generate with Code Snippet in One Click
https://joyceowo.github.io/posts/en/32da78ea09fa80e095dff8f2f76f31f7/