问题
I am trying to build SQL statements within excel.
Sample:
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"
回答1:
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().
回答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.
来源:https://stackoverflow.com/questions/61788842/building-sql-select-statement-within-excel