给SQL语句规范格式

来源:互联网 发布:java mina netty 编辑:程序博客网 时间:2024/06/04 20:03

在写质检规则的时候,有时需要在mysql规则库中查看修改之前写的sql规则

但是不幸的是在mysql规则库中的sql规则没有换行,非常难看,比如下面这个规则:


select 'nav_link" as tn, xxx as fid xxx xx from xx where xxx union all select xx as xx, from where ...


这样的格式真心是看不下去啊(捏一把汗),但是这种问题还常常遇到。

我想把sql语句拷贝下来之后手工换行,调整好格式,弄漂亮一些。

但是挨个去断行也非常麻烦,写个程序吧,干掉它。

对select from where 这一类关键词:换行+输出关键字+换行+留制表符。

对union 这一类关键词:换行+ 输出关键词就可以。

我把无换行的sql语句存在文件in.sql中,程序处理之后输出到out.sql文件中。

sql换行缩进.cpp

程序的结果和手工断行的效果一样一样的,【要想实现一些更细致的缩进可以再改程序。】

代码贴在附件,中文不能正确显示,体验不好,这里再贴一坨。

/*author: huangzhiqiangdate: 2015-4-27功能:把in.sql文件中无换行的sql语句调整换行和缩进后输出到文件out.sql*/#include "stdafx.h"/*vs 环境中添加*/#include<iostream>#include<string>#include<fstream>using namespace std;//keyStr1 需要前换行#define N 7string keyStr1[N] = { "creat", "delete", "drop", "update", "union", "order", "group"};//keyStr2 需要前后换行#define M 3string keyStr2[M] = { "select", "from", "where" };//转化string类型为大写字符string toUpper(string str){string strUp;for (int i = 0; i < str.length(); i++){if (str[i] >= 'a'&&str[i] <= 'z')strUp.push_back(str[i] + 'A' - 'a');elsestrUp.push_back(str[i]);}return strUp;}//判断是否是关键字,是哪种关键字int judgeKey(string str){for (int i = 0; i<N; i++){if (str==keyStr1[i] || str==toUpper(keyStr1[i]) ){return 1;}}for (int i = 0; i<M; i++){if ( str==keyStr2[i] || str==toUpper(keyStr2[i]) ){return 2;}}return 0;}int main(){string fileName,str;//无换行的sql语句的文件名为in.sql(和本程序在同一个目录下)fileName = "in.sql";//从文件in.sql读入freopen(&fileName[0], "r", stdin);//输出到文件out.sqlfreopen("out.sql", "w", stdout);while (cin >> str){/*处理注释行*/if (str.find("/*") != 4294967295)cout << endl << str;/*关键字1 如 union*/else if ( judgeKey(str) == 1 ){cout << endl;cout << str << " ";}/*关键字2 如 select*/else if ( judgeKey(str) == 2 ){cout << endl;cout << str << endl;cout << "\t";}elsecout << str << " ";}//关闭输入重定向fclose(stdin);//关闭输出重定向fclose(stdout);//打开文件,查看输出结果system("out.sql");}



0 0