0

I have the following string containing column names:

string colsToSelect;

This string contains column names (e.g: col1+col2+col3+col4+col5 or col1+col3) and in those columns there are numerical values.

I am using this to get the total of all these columns from database.

SELECT " + colsToSelect + " AS totalVolume " + "FROM myTable

However I need to add nvl(col1,0) to each of the columns as those columns may contain null.

I have achived it like this:

    colsToSelect = colsToSelect.Replace("+", "+nvl(");
    colsToSelect = colsToSelect.Replace("+", ",0)+");
    colsToSelect = "nvl(" + colsToSelect;
    colsToSelect = colsToSelect + ",0)";

This gives me nvl(col1, 0) + nvl(col2, 0) etc.. but I was wondering if there is a better way of achieving this, possibly with LINQ or with sql?

2
  • My solution isn't any better: colsToSelect.Split("+"); Then .ForEach() to pre-pend "nvl(" and append ",0)" and join them back together. No better than what you have. (colsToSelect.Split("+").ForEach(c=> return "+nvl(" + c + ",0)").ToString(); Commented Jun 18, 2013 at 15:03
  • Why is your input coming in as a single string and not a list of strings, or some other data structure? Commented Jun 18, 2013 at 15:08

1 Answer 1

2

You can use string.Split, then string.Join again:

colsToSelect = string.Join("+", 
                    colsToSelect.Split('+')
                                .Select(x => string.Format("nvl({0}, 0)", x)));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.