2

I am trying to build SQL statements within excel.

Sample:

enter image description here

I am trying to build sql statement, but wanted to only add the column when there is a value in the DIM columns. So the SQL looks neat without any syntax error when executed in SQL.

Here how can I eliminate the extra commas before the "from" keyword?

Used this to generate those statements.

="SELECT RET_ID,RET_NM, "&C2&","&D2&","&E2&","&F2&" FROMTABLEX"
0

2 Answers 2

3

Here's an approach which shall work for all versions of Excel

="SELECT RET_ID,RET_NM,"&SUBSTITUTE(TRIM(C2&" "&D2&" "&E2&" "&F2)," ",",")&" FROMTABLEX"

You can add any number of columns inside TRIM().

Sign up to request clarification or add additional context in comments.

2 Comments

Note that should any of the column names have spaces in them (in which case they would have to be escaped), this answer might not generate the correct select statement.
@TimBiegeleisen valid observation!
2

Starting with Office 2019, the TEXTJOIN function is very helpful here, because it lets you build a CSV string with optional components:

="SELECT RET_ID, RET_NM, "&TEXTJOIN(", ", TRUE, C2, D2, E2, F2)&" FROM TABLEX"

If you are using an earlier version of Excel, you can still pull off what you want, by using IF() combined with CONCATENATE(), but the logic is more verbose.

1 Comment

Or a little shorter: ="SELECT RET_ID, RET_NM, "&TEXTJOIN(", ",1,C2:F2)&" FROM TABLEX"

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.