在c#代码中编写SQL查询的最佳实践是什么?

时间:2010-07-04 21:12:31

标签: c# coding-style

在我当前的项目中,我正在使用SQL CE。由于它不支持存储过程,我必须在存储库中编写sql查询。

选项1:

StringBuilder query = new StringBuilder();
query.Append("SELECT");
query.Append("    c.CUSTOMER_ID,");
query.Append("    COALESCE (c.FIRST_NAME, '') + ' ' + COALESCE (c.LAST_NAME, '') AS FULL_NAME");
query.Append("    ct.NAME as CUSTOMER_TYPE");
query.Append("FROM ");
query.Append("    CT_CUSTOMER_TYPE AS ct INNER JOIN CUSTOMER AS c ON ct.CUSTOMER_TYPE_ID = c.CUSTOMER_TYPE_ID");

选项2:

string query = "SELECT c.CUSTOMER_ID, COALESCE (c.FIRST_NAME, '') + ' ' + COALESCE (c.LAST_NAME, '') AS FULL_NAME, ct.NAME as CUSTOMER_TYPE FROM CT_CUSTOMER_TYPE AS ct INNER JOIN CUSTOMER AS c ON ct.CUSTOMER_TYPE_ID = c.CUSTOMER_TYPE_ID";

选项1看起来更具可读性,尤其是当我有10个以上的表连接时,但选项2更快。
我应该接受哪种选择?在这种情况下,最佳做法是什么?

7 个答案:

答案 0 :(得分:15)

选项2可能会快几毫秒,但是当您在数据库中添加实际执行的时间(几毫秒)时,几个额外的纳秒几乎不会记录为噪声。

无论如何,还有另一种选择是两全其美的:@ -strings:

string query = @"
    SELECT
        c.CUSTOMER_ID,
        COALESCE (c.FIRST_NAME, ''_ + ' ' + COALESCE (c.LAST_NAME, '') AS FULL_NAME
        ct.NAME as CUSTOMER_TYPE
    FROM
        CT_CUSTOMER_TYPE AS ct INNER JOIN CUSTOMER AS c
            ON ct.CUSTOMER_TYPE_ID = c.CUSTOMER_TYPE_ID
    ";

答案 1 :(得分:5)

选项3 - 使用verbatim string literals

string query = @"
SELECT 
    c.CUSTOMER_ID,
    COALESCE (c.FIRST_NAME, '') + ' ' + COALESCE (c.LAST_NAME, '') AS FULL_NAME,
    ct.NAME as CUSTOMER_TYPE
FROM 
    CT_CUSTOMER_TYPE AS ct 
  INNER JOIN CUSTOMER AS c 
    ON ct.CUSTOMER_TYPE_ID = c.CUSTOMER_TYPE_ID";

答案 2 :(得分:4)

我将SQL字符串放入资源文件中,它允许轻松编辑多行查询,并提供对该查询的强类型命名访问,即使使用IntelliSence工具提示也是如此。

答案 3 :(得分:0)

我总是使用第二种方法,因为它更快。使用第一种方法会占用过多行代码,从而导致更大的开销。

答案 4 :(得分:0)

答案 5 :(得分:0)

我已经习惯了这种方法:

  1. 使用+,此运算符将在编译时添加字符串,而不是在运行时(https://docs.microsoft.com/en-us/dotnet/csharp/how-to/concatenate-multiple-strings
  2. 此语法在运行时不应更改,请使用const。
  3. 使用缩进格式可以很好地格式化脚本。

目标是保持可读性并减少数据传输,并且没有运行时性能成本:),完美。

    string const query = 
    "SELECT c.CUSTOMER_ID, " +
        "COALESCE (c.FIRST_NAME, ''_ + ' ' + COALESCE (c.LAST_NAME, '') AS FULL_NAME, " +
        "ct.NAME as CUSTOMER_TYPE " +
    "FROM CT_CUSTOMER_TYPE AS ct INNER JOIN CUSTOMER AS c " +
        "ON ct.CUSTOMER_TYPE_ID = c.CUSTOMER_TYPE_ID;";

答案 6 :(得分:-1)

为什么不选择3:

"Select bla bla bla"
"bla bla bla"
"...."

一个长文字,分成多行。