Static code analysis
There is support for running static code analysis during build. The SDK includes the following sets of rules:
Enable static code analysis
Static code analysis can be enabled by adding the RunSqlCodeAnalysis property to the project file:
<Project Sdk="MSBuild.Sdk.SqlProj/4.2.0">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<RunSqlCodeAnalysis>True</RunSqlCodeAnalysis>
<CodeAnalysisRules>-SqlServer.Rules.SRD0006;-SqlServer.Rules.SRN*</CodeAnalysisRules>
</PropertyGroup>
</Project>
Note
The target framework must be set to net8.0 or net10.0 when using additional NuGet-based rules.
An XML file with the analysis results is created in the output folder.
The optional CodeAnalysisRules property allows you to disable individual rules or groups of rules for the entire project.
Suppress rules per file
You can also disable rules per file. Add a StaticCodeAnalysis.SuppressMessages.xml file to the project root, with contents similar to this:
<?xml version="1.0" encoding="utf-8" ?>
<StaticCodeAnalysis version="2" xmlns="urn:Microsoft.Data.Tools.Schema.StaticCodeAnalysis">
<SuppressedFile FilePath="Procedures\sp_Test.sql">
<SuppressedRule Category="Microsoft.Rules.Data" RuleId="SR0001" />
</SuppressedFile>
</StaticCodeAnalysis>
Any rule violations found during analysis are reported as build warnings.
Treat rule violations as errors
Individual rule violations or groups of rules can be configured to be reported as build errors as shown below.
<Project Sdk="MSBuild.Sdk.SqlProj/4.2.0">
<PropertyGroup>
<RunSqlCodeAnalysis>True</RunSqlCodeAnalysis>
<CodeAnalysisRules>+!SqlServer.Rules.SRN0005;+!SqlServer.Rules.SRD*</CodeAnalysisRules>
</PropertyGroup>
</Project>
Use additional rule packages
We know of the following public rules NuGet package that you can add to your project.
<ItemGroup>
<PackageReference Include="ErikEJ.DacFX.SqlServer.Rules" Version="5.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
The rules in the package are based on these older repositories:
Create your own custom rule packages
You can also build your own rules. For an example of how to build a custom rule, see this blog post.
To publish your own custom rules, pack your rule .dll in a NuGet package as shown in this rule project file from GitHub.