工作中遇到一个场景,需要用VBA把SQL语句重新美观格式化一下,本来想直接调用本地的SQLWORKBENCH工具来实现这一功能,无奈找不到command参数,不能被VBA直接调用,作罢.
网上找到可以直接调用网站的API用VBA 调用http post可以来实现.
网页API说明:
https://github.com/sqlparser/sql-pretty-printer/wiki/SQL-FaaS-API-manual
里面必选的参数 rqst_input_sql,传入带转化的SQL语句.
Response里面关注的参数,rspn_output_fmt 为转化完之后的SQL语句.
VBA函数代码如下:
Function CallSQLFormat(ByVal SQL As String) Dim http Set http = CreateObject("Microsoft.XMLHTTP") http.Open "POST", "http://www.gudusoft.com/format.php", False http.setRequestHeader "Content-Type", "application/x-www-form-urlencoded" http.send "rqst_input_sql=" & SQL If http.Status = 200 Then Resp_text = http.responseText istart = InStr(Resp_text, "rspn_formatted_sql") iend = InStr(Resp_text, "}") CallSQLFormat = Replace(Mid(Resp_text, istart + 18 + 2 + 1, iend - istart - 22), "\n", vbLf) Else CallSQLFormat = SQL End If End Function