In relation with this question about how to write long SQL queries within C#., the solution suggested that a long sql query should be written 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
";
That makes me curious about another related question. Can I use substitution somehow? That is, how would I manage if say the table name changes but the query remains the same? Do I have to fall back to using the other approach of building a string using string concatenations or is there a more elegant way?
A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals.
A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello".
In C#, a verbatim string is created using a special symbol @. @ is known as a verbatim identifier. If a string contains @ as a prefix followed by double quotes, then compiler identifies that string as a verbatim string and compile that string.
The @ character in this instance defines a verbatim string literal. Simple escape sequences (such as "\\" for a backslash), hexadecimal escape sequences (such as "\x0041" for an uppercase A), and Unicode escape sequences (such as "\u0041" for an uppercase A) are interpreted literally.
You might consider using LINQ to SQL, if you haven't already.
Answering the actual question, you could use string.Format
as the others have mentioned if you're creating the query. If you wish to modify an existing string, try using string.Replace
or Regex.Replace
as described here. That is:
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");
Why not make use of 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 invoke
string real_query = string.Format(query, tblName1, tblName2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With