Replacing inside shorthand lines?

In connection with this question about how to write long SQL queries in C #., The solution suggested writing a long sql query as:

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

This makes me interested in another related issue. Is there any way to replace the substitution? That is, how can I control if we say the table name changes, but the query remains the same? Should I go back to a different approach to building strings using string concatenations or is there a more elegant way?

+5
source share
3 answers

Why not use string.Format? In the specific example you gave, you could do something like

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

And the challenge

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

, 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.

+4

LINQ to SQL, .

, string.Format, , . , string.Replace Regex.Replace, . :

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");
+1

All Articles