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

前端之家收集整理的这篇文章主要介绍了在c#代码中编写SQL查询的最佳实践是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我目前的项目中,我正在使用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,'') 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更快.
我应该接受哪个选项,在这种情况下最佳做法是什么?

解决方法

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

在任何情况下,还有另一种选择,这是两个世界中最好的选择:@ -strings:

string query = @"
    SELECT
        c.CUSTOMER_ID,''_ + ' ' + 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
    ";

猜你在找的C#相关文章