sql-server 在逐字字串常值内进行替代?

r6hnlfcb  于 2022-10-31  发布在  其他
关注(0)|答案(4)|浏览(163)

关于如何在C#中编写长SQL查询的question,该解决方案建议长SQL查询应编写为:

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
    ";

这让我对另一个相关的问题感到好奇。我能以某种方式使用替换吗?也就是说,如果表名发生了变化,但查询保持不变,我该如何处理?我是否必须使用另一种方法,即使用字符串连接来构建字符串,或者有没有更优雅的方法?

7rtdyuoh

7rtdyuoh1#

为什么不使用string.format呢?在您给出的特定示例中,您可以执行以下操作

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

和调用

string real_query = string.Format(query, tblName1, tblName2);
rsaldnfx

rsaldnfx2#

是的,您可以使用String.Format方法。

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

string endQuery = String.Format(query, custtype, cust);

String.Format方法将用字符串后面的参数按顺序替换由{x}标识的参数,因此{0}将替换为custtype的值,{1}将替换为cust的值。

x6yk4ghg

x6yk4ghg3#

如果您还没有使用LINQ to SQL,您可以考虑使用它。
回答实际的问题,你可以使用string.Format,就像其他人在创建查询时提到的那样。如果你想修改一个现有的字符串,试着使用string.ReplaceRegex.Replace,就像here描述的那样。也就是:

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
    ";
query.Replace("CT_CUSTOMER_TYPE", "NEW_TABLE_NAME");
lfapxunr

lfapxunr4#

内插逐字字符串

string filter = "name LIKE '%volvo%'";
string strSQL = $@"
    SELECT  code, name
    FROM    tb_car
    WHERE   {filter}
    ";

相关问题