views:

184

answers:

6

On my current project I'm using SQL CE. Since it doesn't have support for stored procedures I have to write sql queries inside repository.

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

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

Option 1 seems like a much more readable, especially when I have 10+ tables in join, but option 2 is faster.
Which option should I accept and what's the best practice in this case?

A: 

Why not option 3:

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

one long literal, split to many lines.

Pavel Radzivilovsky
A: 

I always use the second method as it is much faster. You use up too many lines of code with the first method, leading to a larger overhead.

Jason Edwards
+3  A: 

Option 3 - use 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";
Oded
+4  A: 

Option 2 may be a few nanoseconds faster, but when you add the time to actually execute in the database (several milliseconds) a few extra nanaoseconds barely registers as noise.

In any case, there is another option that's the best of both worlds: @-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
    ";
Dean Harding
I completely forgot verbatim strings. Thank you.
šljaker
+3  A: 

I puts SQL string into resource files, it allows easy edit multiline queries, and provides strongly typed named access to that queries even with IntelliSence tooltips.

STO
Excellent idea!
šljaker
This also means that the app has to go and retrieve the resource, could be a minor performance hit there too.
rockinthesixstring
This is what I do for complex SQL commands. It allows you to edit the SQL as freely as you would in Management Studio, and provides proper syntax colouring. The performance penalty for reading the embedded resource is negligible compared to a database hit.
Christian Hayter
your right, it is negligible compared to a db hit... it's about as significant as using the StringBuilder.
rockinthesixstring