Building SQL SELECT statement within EXCEL

我与影子孤独终老i 提交于 2021-02-10 09:45:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!