user2653353
user2653353

Reputation: 105

Building SQL SELECT statement within EXCEL

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"

Upvotes: 2

Views: 79

Answers (2)

shrivallabha.redij
shrivallabha.redij

Reputation: 5902

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().

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522471

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.

Upvotes: 2

Related Questions