1. 为什么要格式化 SQL 语句
提高可读性:格式化的 SQL 语句更易于阅读和理解。
便于维护:整洁的代码更容易维护和更新。
减少错误:清晰的格式有助于减少语法错误和逻辑错误。
统一风格:团队中统一的代码风格有助于提高协作效率。
2. 手动格式化 SQL 语句
示例代码
csharp
string sql = @"
SELECT EmployeeID, FirstName, LastName
FROM Employees
WHERE DepartmentID = @DepartmentId
ORDER BY LastName, FirstName";
3. 使用字符串构建器
示例代码
csharp
var sqlBuilder = new StringBuilder();
sqlBuilder.AppendLine("SELECT EmployeeID, FirstName, LastName");
sqlBuilder.AppendLine("FROM Employees");
sqlBuilder.AppendLine("WHERE DepartmentID = @DepartmentId");
sqlBuilder.AppendLine("ORDER BY LastName, FirstName");
string sql = sqlBuilder.ToString();
4. 使用字符串插值和格式化
示例代码
csharp
int departmentId = 5;
string sql = $@"
SELECT EmployeeID, FirstName, LastName
FROM Employees
WHERE DepartmentID = {departmentId}
ORDER BY LastName, FirstName";
5. 使用参数化查询
示例代码
csharp
string sql = @"
SELECT EmployeeID, FirstName, LastName
FROM Employees
WHERE DepartmentID = @DepartmentId
ORDER BY LastName, FirstName";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("@DepartmentId", departmentId);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"{reader["EmployeeID"]} {reader["FirstName"]} {reader["LastName"]}");
}
}
6. 使用 ORM 工具
示例代码
csharp
using (var context = new MyDbContext())
{
var query = context.Employees
.Where(e => e.DepartmentID == departmentId)
.OrderBy(e => e.LastName)
.ThenBy(e => e.FirstName)
.Select(e => new { e.EmployeeID, e.FirstName, e.LastName });
foreach (var employee in query)
{
Console.WriteLine($"{employee.EmployeeID} {employee.FirstName} {employee.LastName}");
}
}
7. 使用 SQL 格式化工具
示例
8. 编写自定义格式化程序
示例代码
csharp
public static string FormatSql(string sql)
{
var lines = sql.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var formattedLines = new List<string>();
var indentLevel = 0;
foreach (var line in lines)
{
string trimmedLine = line.TrimStart();
if (trimmedLine.StartsWith("SELECT") || trimmedLine.StartsWith("UPDATE") || trimmedLine.StartsWith("DELETE") || trimmedLine.StartsWith("INSERT"))
{
indentLevel = 0;
}
var indent = new String(' ', 4 * indentLevel);
formattedLines.Add(indent + trimmedLine);
if (trimmedLine.StartsWith("FROM") || trimmedLine.StartsWith("JOIN") || trimmedLine.StartsWith("WHERE"))
{
indentLevel++;
}
}
return String.Join(Environment.NewLine, formattedLines);
}
结论
往期精品推荐: