SQL 模糊查询

本文详细介绍了SQL中的模糊查询方法,包括使用LIKE关键字结合通配符进行的查询技巧。阐述了四种主要的匹配模式:%表示任意数量的字符,_表示单个任意字符,[]表示指定的一个字符,[^]表示除了指定字符之外的任何一个字符。并提供了实用的查询示例。

在进行数据库查询时,有完整查询和模糊查询之分。

一般模糊查询语句如下:

SELECT 字段 FROM 表 WHERE 某字段 Like 条件



其中关于条件,SQL提供了四种匹配模式:

1,% :表示任意0个或多个字符。可匹配任意类型和长度的字符,有些情况下若是中文,请使用两个百分号(%%)表示。

比如 SELECT * FROM [user] WHERE u_name LIKE '%三%'

将会把u_name为“张三”,“张猫三”、“三脚猫”,“唐三藏”等等有“三”的记录全找出来。

另外,如果需要找出u_name中既有“三”又有“猫”的记录,请使用and条件
SELECT * FROM [user] WHERE u_name LIKE '%三%' AND u_name LIKE '%猫%'

若使用 SELECT * FROM [user] WHERE u_name LIKE '%三%猫%'
虽然能搜索出“三脚猫”,但不能搜索出符合条件的“张猫三”。

2,_ : 表示任意单个字符。匹配单个任意字符,它常用来限制表达式的字符长度语句:

比如 SELECT * FROM [user] WHERE u_name LIKE '_三_'
只找出“唐三藏”这样u_name为三个字且中间一个字是“三”的;

再比如 SELECT * FROM [user] WHERE u_name LIKE '三__';
只找出“三脚猫”这样name为三个字且第一个字是“三”的;


3,[ ] :表示括号内所列字符中的一个(类似正则表达式)。指定一个字符、字符串或范围,要求所匹配对象为它们中的任一个。

比如 SELECT * FROM [user] WHERE u_name LIKE '[张李王]三'
将找出“张三”、“李三”、“王三”(而不是“张李王三”);

如 [ ] 内有一系列字符(01234、abcde之类的)则可略写为“0-4”、“a-e”
SELECT * FROM [user] WHERE u_name LIKE '老[1-9]'
将找出“老1”、“老2”、……、“老9”;

4,[^ ] :表示不在括号所列之内的单个字符。其取值和 [] 相同,但它要求所匹配对象为指定字符以外的任一个字符。

比如 SELECT * FROM [user] WHERE u_name LIKE '[^张李王]三'
将找出不姓“张”、“李”、“王”的“赵三”、“孙三”等;

SELECT * FROM [user] WHERE u_name LIKE '老[^1-4]';
将排除“老1”到“老4”,寻找“老5”、“老6”、……

5,查询内容包含通配符时 

由于通配符的缘故,导致我们查询特殊字符“%”、“_”、“[”的语句无法正常实现,而把特殊字符用“[ ]”括起便可正常查询。据此我们写出以下函数:


function sqlencode(str)
str=replace(str,"[","[[]") '此句一定要在最前
str=replace(str,"_","[_]")
str=replace(str,"%","[%]")
sqlencode=str
end function

在查询前将待查字符串先经该函数处理即可,并且在网页上连接数据库用到这类的查询语句时侯要注意:

如Select * FROM user Where name LIKE '老[^1-4]';上面 《'》老[^1-4]《'》是要有单引号的,别忘了,我经常忘!


access

在近日的写Web程序时用到了Access的模糊查询,在Acces里写代码怎么也找不到记录,后来才起来原来Acess和SqlServer的模糊查询是有特别的
条件:查找表A 的Name字段中包括 "B" 的记当
在Access里的代码:

1 Select * from a where name like '*b*'Sql Server查询分析器的代码
Select * from a where name like '%b%'这时你会发现Access里可以找到相关的记录,但把'*'必成'%'就找不到了,原因是Access的模糊查询是'?','*'
和Sql server不一样
以上只是在数据库中的代码,如果要写在程序里可就不能用.'*'了,还是要用'%'
程序:
strSql="select * from a where name like '%b%'"所以如果有朋友和我一样喜欢先在数据库中代码测试,那可就要注意了!!

----------------------------------------------------------------------------------------------------------

SQL模糊查询,使用like比较关键字,加上SQL里的通配符,请参考以下: 
1、LIKE'Mc%' 将搜索以字母 Mc 开头的所有字符串(如 McBadden)。 
2、LIKE'%inger' 将搜索以字母 inger 结尾的所有字符串(如 Ringer、Stringer)。 
3、LIKE'%en%' 将搜索在任何位置包含字母 en 的所有字符串(如 Bennet、Green、McBadden)。 
4、LIKE'_heryl' 将搜索以字母 heryl 结尾的所有六个字母的名称(如 Cheryl、Sheryl)。 
5、LIKE'[CK]ars[eo]n' 将搜索下列字符串:Carsen、Karsen、Carson 和 Karson(如 Carson)。 
6、LIKE'[M-Z]inger' 将搜索以字符串 inger 结尾、以从 M 到 Z 的任何单个字母开头的所有名称(如 Ringer)。 
7、LIKE'M[^c]%' 将搜索以字母 M 开头,并且第二个字母不是 c 的所有名称(如MacFeather)。 
------------------------------------------------- 
下 面这句查询字符串是我以前写的,根据变量 zipcode_key 在邮政编码表 zipcode 中查询对应的数据,这句是判断变量 zipcode_key 为非数字时的查询语句,用 % 来匹配任意长度的字符串,从表中地址、市、省三列中查询包含关键字的所有数据项,并按省、市、地址排序。这个例子比较简单,只要你理解了方法就可以写出更 复杂的查询语句。 

sql = "select * from zipcode where (address like'%" & zipcode_key & "%') or (city like'%" & zipcode_key & "%') or (province like'%" & zipcode_key & "%') order by province,city,address

存储过程中使用模糊查询的例子: SELECT * FROM Questions where QTitle like ' % '+ @KeyWord +' % ' and IsFinish = @IsFinsih
语句中成对的方括号 是书写格式的关键。
<!-- ==================== 主表单结构 ==================== --> <table align="center" border="0" cellpadding="0" cellspacing="0" class="tableForm" style="table-layout: fixed;"> <colgroup> <col width="80" /> <col /><!--hide4phone.start--> <col width="80" /> <col width="380" /><!--hide4phone.end--> </colgroup> <tbody> <tr> <td style="text-align: right;"> <span style="color: red;">*</span>Subject:</td> <td dbf.type="required" id="dbf.subject"> </td> <!--show4phone.start--> </tr> <tr><!--show4phone.end--> <td style="text-align: right;"> Status:</td> <td><span id="mapping.dbf.procXSource"> </span>       Responsor: <span id="mapping.dbf.responsorSource"> </span>       Participants: <span id="mapping.dbf.participantsSource"> </span></td> </tr> </tbody> </table> <div> </div> <!-- ==================== 页面标题 ==================== --> <div style="text-align: center;"> <h1><img src="../common/logo.png" /> [报价历史查询内勤用]</h1> </div> <div>[Design form here, based on the template below, or customized by yourself after the template removed]</div> <!-- ==================== 查询输入区域 ==================== --> <table align="center" border="0" cellpadding="0" cellspacing="0" class="tableListBorder" style="table-layout: fixed; width: 928px;"> <colgroup> <col width="130" /> <col /><!--hide4phone.start--> <col width="130" /> <col width="330" /><!--hide4phone.end--> </colgroup> <tbody> <tr> <td colspan="4" style="background-color: lightyellow;"> </td> </tr> <tr> <td class="fieldLabel" style="text-align: center; width: 147px;"><span style="color: red;">*</span> username</td> <td id="username" style="width: 210px;"> </td> <!--show4phone.start--> </tr> <tr><!--show4phone.end--> <td class="fieldLabel" style="text-align: center; width: 63px;"><span style="color: red;">*</span> id</td> <td id="ID" style="width: 254px;"> </td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">项目名称</td> <td id="项目名称" style="width: 210px;"> </td> <td class="fieldLabel" style="text-align: center;">装置名称</td> <td id="装置名称" style="width: 254px;"> </td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">Customer Name</td> <td id="CustomerName" style="width: 210px;"> </td> <td class="fieldLabel" style="text-align: center;">E-NO/序列号</td> <td id="ENO" style="width: 254px;"> </td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">产品描述</td> <td id="产品描述" style="width: 210px;"> </td> <td class="fieldLabel" style="text-align: center;">Remark</td> <td id="Remark" style="width: 254px;"> </td> </tr> </tbody> </table> <!-- ==================== 查询结果表格容器 ==================== --> <div id="resultTableContainer" style="margin-top: 20px; padding: 0 10px;"><!-- 动态表格将插入到这里 --></div> <!-- ==================== 手机适配区域(可选)==================== --> <div class="slide4phone"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="tableListBorder2" style="table-layout: fixed;"> <colgroup> <col width="460" /> <col width="140" /> <col /> </colgroup> </table> </div> <!-- ==================== 查询按钮 ==================== --> <div style="text-align: center; margin: 20px 0;">        <input id="idslist" name="idslist" type="hidden" />                                                                   <strong> <input id="check" name="check" onclick="clickData()" type="button" value="check个人记录" /> </strong></div> <!-- ==================== 移动端表格占位 ==================== --> <div class="slide4phone2" id="reptable"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="tableListBorder2" style="width: 1300px;"> </table> </div> <script language="javascript"> function clickData() { // 获取输入框的值并添加通配符 % 用于模糊查询 var username = '%' + document.getElementById('username').textContent.trim() + '%'; var 项目name = '%' + document.getElementById('项目名称').textContent.trim() + '%'; var 装置name = '%' + document.getElementById('装置名称').textContent.trim() + '%'; var CustomerName = '%' + document.getElementById('CustomerName').textContent.trim() + '%'; var ENO = '%' + document.getElementById('ENO').textContent.trim() + '%'; var Remark = '%' + document.getElementById('Remark').textContent.trim() + '%'; var Product描述 = '%' + document.getElementById('产品描述').textContent.trim() + '%'; // 构建 SQL 查询语句(注意字段名和表名需正确) var sqlQuery2 = "SELECT Subject,Status,申请人,申请日期,产品类别,其他,type,内勤,系统,customer,ProjectName,DeviceName,新产品,[E-NO/序列号],目标价,数量,产地,含税报价,HandlerRemark,Remark,描述 " + "FROM X_BPM_DWH_819 " + "WHERE ProjectName LIKE '" + 项目name + "' " + "AND DeviceName LIKE '" + 装置name + "' " + "AND customer LIKE '" + CustomerName + "' " + "AND [E-NO/序列号] LIKE '" + ENO + "' " + "AND Remark LIKE '" + Remark + "' " + "AND 描述 LIKE '" + Product描述 + "'"; // 调用后台服务获取数据(假设返回的是二维数组) eval("var arr=" + service("common.js", "getDbsRecords", sqlQuery2, "array")); // 清空之前的结果 var container = document.getElementById("resultTableContainer"); container.innerHTML = ""; if (!arr || arr.length === 0) { container.innerHTML = "<p>未找到匹配的数据。</p>"; return; } // 创建表格 var table = document.createElement("table"); table.className = "tableListBorder"; table.style.width = "100%"; table.style.tableLayout = "fixed"; table.setAttribute("border", "1"); table.setAttribute("cellpadding", "5"); table.setAttribute("cellspacing", "0"); // 添加表头(使用 arr[0] 的键作为列名,或手动定义) var thead = document.createElement("thead"); var headerRow = document.createElement("tr"); // 手动定义表头文字(与 SELECT 字段顺序一致) var headers = [ "Subject", "Status", "申请人", "申请日期", "产品类别", "其他", "类型", "内勤", "系统", "客户", "项目名称", "装置名称", "新产品", "E-NO/序列号", "目标价", "数量", "产地", "含税报价", "处理备注", "备注", "描述" ]; headers.forEach(function (text) { var th = document.createElement("th"); th.style.backgroundColor = "#f0f0f0"; th.style.textAlign = "center"; th.style.fontSize = "14px"; th.textContent = text; headerRow.appendChild(th); }); thead.appendChild(headerRow); table.appendChild(thead); // 添加数据行 var tbody = document.createElement("tbody"); arr.forEach(function (row) { var tr = document.createElement("tr"); for (var i = 0; i < row.length; i++) { var td = document.createElement("td"); td.style.padding = "5px"; td.style.fontSize = "13px"; td.style.wordBreak = "break-word"; td.textContent = row[i] || ""; tr.appendChild(td); } tbody.appendChild(tr); }); table.appendChild(tbody); // 将表格插入容器 container.appendChild(table); } </script> 修改代码 第二次按查询按钮后 会重置生成结果
09-24
<!-- ==================== 主表单结构 ==================== --> <table align="center" border="0" cellpadding="0" cellspacing="0" class="tableForm" style="table-layout: fixed;"> <colgroup> <col width="80" /> <col /><!--hide4phone.start--> <col width="80" /> <col width="380" /><!--hide4phone.end--> </colgroup> <tbody> <tr> <td style="text-align: right;"> <span style="color: red;">*</span>Subject:</td> <td dbf.type="required" id="dbf.subject"> </td> <!--show4phone.start--> </tr> <tr><!--show4phone.end--> <td style="text-align: right;"> Status:</td> <td><span id="mapping.dbf.procXSource"> </span>       Responsor: <span id="mapping.dbf.responsorSource"> </span>       Participants: <span id="mapping.dbf.participantsSource"> </span></td> </tr> </tbody> </table> <div> </div> <!-- ==================== 页面标题 ==================== --> <div style="text-align: center;"> <h1><img src="../common/logo.png" /> [报价历史查询内勤用]</h1> </div> <div>[Design form here, based on the template below, or customized by yourself after the template removed]</div> <!-- ==================== 查询输入区域 ==================== --> <table align="center" border="0" cellpadding="0" cellspacing="0" class="tableListBorder" style="table-layout: fixed; width: 928px;"> <colgroup> <col width="130" /> <col /><!--hide4phone.start--> <col width="130" /> <col width="330" /><!--hide4phone.end--> </colgroup> <tbody> <tr> <td colspan="4" style="background-color: lightyellow;"> </td> </tr> <tr> <td class="fieldLabel" style="text-align: center; width: 147px;"><span style="color: red;">*</span> username</td> <td id="username" style="width: 210px;"> </td> <!--show4phone.start--> </tr> <tr><!--show4phone.end--> <td class="fieldLabel" style="text-align: center; width: 63px;"><span style="color: red;">*</span> id</td> <td id="ID" style="width: 254px;"> </td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">项目名称</td> <td id="项目名称" style="width: 210px;"> </td> <td class="fieldLabel" style="text-align: center;">装置名称</td> <td id="装置名称" style="width: 254px;"> </td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">Customer Name</td> <td id="CustomerName" style="width: 210px;"> </td> <td class="fieldLabel" style="text-align: center;">E-NO/序列号</td> <td id="ENO" style="width: 254px;"> </td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">产品描述</td> <td id="产品描述" style="width: 210px;"> </td> <td class="fieldLabel" style="text-align: center;">Remark</td> <td id="Remark" style="width: 254px;"> </td> </tr> </tbody> </table> <!-- ==================== 查询结果表格容器 ==================== --> <div id="resultTableContainer" style="margin-top: 20px; padding: 0 10px;"><!-- 动态表格将插入到这里 --></div> <!-- ==================== 手机适配区域(可选)==================== --> <div class="slide4phone"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="tableListBorder2" style="table-layout: fixed;"> <colgroup> <col width="460" /> <col width="140" /> <col /> </colgroup> </table> </div> <!-- ==================== 查询按钮 ==================== --> <div style="text-align: center; margin: 20px 0;">        <input id="idslist" name="idslist" type="hidden" />                                                                   <strong> <input id="check" name="check" onclick="clickData()" type="button" value="check个人记录" /> </strong></div> <!-- ==================== 移动端表格占位 ==================== --> <div class="slide4phone2" id="reptable"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="tableListBorder2" style="width: 1300px;"> </table> </div> <script language="javascript"> function clickData(){ var aa='%'+$("username").value().trim()+'%'; var 项目name= '%'+$("项目名称").value().trim()+'%'; var 装置name= '%'+$("装置名称").value().trim()+'%'; var CustomerName= '%'+$("CustomerName").value().trim()+'%'; var ENO= '%'+$("ENO").value().trim()+'%'; var Remark= '%'+$("Remark").value().trim()+'%' var Product描述 = '%'+$("产品描述").value().trim()+'%' // var sqlQuery2 = "SELECT Subject,Status,申请人,申请日期,产品类别,其他,type,内勤,系统,customer,ProjectName,DeviceName,新产品,[E-NO/序列号],目标价,数量,产地,含税报价,HandlerRemark,Remark FROM X_BPM_DWH_819 " var sqlQuery2 = "SELECT Subject,Status,申请人,申请日期,产品类别,其他,type,内勤,系统,customer,ProjectName,DeviceName,新产品,[E-NO/序列号],目标价,数量,产地,含税报价,HandlerRemark,Remark,描述 FROM X_BPM_DWH_819 where ProjectName like '" +项目name+ "' and DeviceName like '"+ 装置name + "' and customer like '"+CustomerName+ "' and [E-NO/序列号] like '"+ENO+ "' and Remark like '"+Remark+ "' and 描述 like '"+Product描述+"'" eval("var arr="+service("common.js","getDbsRecords",sqlQuery2,"array")); alert(arr) 修改页面让 arr结果动态在页面上显示结果
09-24
<table align="center" border="0" cellpadding="0" cellspacing="0" class="tableForm" style="table-layout: fixed;"> <colgroup> <col width="80" /> <col /><!--hide4phone.start--> <col width="80" /> <col width="380" /><!--hide4phone.end--> </colgroup> <tbody> <tr> <td style="text-align: right;"> <span style="color: rgb(255, 0, 0);">*</span>Subject:</td> <td dbf.type="required" id="dbf.subject"> </td> <!--show4phone.start></tr><tr><show4phone.end--> <td style="text-align: right;"> Status:</td> <td><span id="mapping.dbf.procXSource"> </span>      Responsor: <span id="mapping.dbf.responsorSource"> </span>      Participants: <span id="mapping.dbf.participantsSource"> </span></td> </tr> </tbody> </table> <div> </div> <div style="text-align: center;"> <h1><img src="../common/logo.png" /> [Form Name]</h1> </div> <div>[Design form here, based on the template below, or customized by yourself after the template removed]</div> <table align="center" border="0" cellpadding="0" cellspacing="0" class="tableListBorder" style="table-layout: fixed;"> <colgroup> <col width="130" /> <col /><!--hide4phone.start--> <col width="130" /> <col width="330" /><!--hide4phone.end--> </colgroup> <tbody> <tr> <td colspan="4" colspan4phone="2" dbf.source="" dbf.type="" style="background-color: lightyellow;"> <strong>[Brief Information]</strong></td> </tr> <tr> <td class="fieldLabel" style="text-align: center; width: 147px;"><span style="color: red;">*</span> username</td> <td id="username" style="width: 210px;"> </td> <!--show4phone.start--> </tr> <tr><!--show4phone.end--> <td class="fieldLabel" style="text-align: center; width: 63px;"><span style="color: red;">*</span> id</td> <td id="ID" style="width: 254px;"> </td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">项目名称</td> <td id="项目名称" style="width: 210px;"> </td> <td class="fieldLabel" style="text-align: center;">装置名称</td> <td id="装置名称" style="width: 254px;"> </td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">Customer Name</td> <td id="CustomerName" style="width: 210px;"> </td> <td class="fieldLabel" style="text-align: center;">E-NO/序列号</td> <td id="ENO号" style="width: 254px;"> </td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">产品描述</td> <td id="产品描述" style="width: 210px;"> </td> <td class="fieldLabel" style="text-align: center;">Remark</td> <td id="Remark" style="width: 254px;"> </td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">Subject</td> <td id="subjectid" style="width: 210px;"> </td> <td class="fieldLabel" dbf.source="" dbf.type="" id="" style="text-align: center;"> </td> <td dbf.source="" dbf.type="" id="" style="width: 254px;"> </td> </tr> <tr> <td colspan="4" colspan4phone="2" dbf.source="" dbf.type="" style="background-color: lightyellow;"><strong> </strong><strong>[Detailed Information]</strong></td> </tr> </tbody> </table> <div style="text-align: center; margin: 20px 0;">        <input id="idslist" name="idslist" type="hidden" />  <input id="sql内容" name="sql内容" type="hidden" />                                                                 <strong> <input id="check" name="check" onclick="clickData()" type="button" value="check记录" /> </strong> <strong> <input id="check2" name="check2" onclick="clickData2()" type="button" value="下载结果" /> </strong></div> <!-- ==================== 移动端表格占位(暂不使用)==================== --><!-- ==================== 查询结果表格容器 ==================== --> <div id="resultTableContainer" style="margin-top: 20px; padding: 0 10px; min-height: 20px;"><!-- 动态表格将插入到这里 --></div> <div class="slide4phone2" id="reptable" style="display:none;"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="tableListBorder2" style="width: 1300px;"> </table> </div> <!-- ==================== 核心脚本:查询与渲染 ==================== --><script language="javascript"> function clickData() { if (window.__isQuerying) return; window.__isQuerying = true; try { var enonumber = $("ENO号")?.value ? $("ENO号").value().trim() : ""; if (!enonumber) { alert("请输入搜索内容"); return; } console.log("【原始输入】", enonumber); function escapeSql(str) { return String(str || '').replace(/'/g, "''"); } // ✅ 正确构建模糊匹配模式 const searchPattern = '%' + escapeSql(enonumber) + '%'; // ✅ 清洗字段中的各种隐藏字符 const cleanedField = ` REPLACE( REPLACE( REPLACE( REPLACE( ISNULL([ENO序列号], ''), CHAR(10), ''), CHAR(13), ''), CHAR(9), ''), ' ', '') `; var sql = ` SELECT TOP 100 Subject, Status, 申请人, 申请日期, 产品类别, 其他, type, 内勤, 系统, customer, ProjectName, DeviceName, 新产品, [ENO序列号], 目标价, 数量, 产地, 含税报价, HandlerRemark, Remark, 描述 FROM X_BPM_DWH_819_InquiryLines WHERE ${cleanedField} LIKE '${searchPattern}' ORDER BY 申请日期 DESC `; console.log("【执行SQL", sql); var rawResult = service("common.js", "getDbsRecords", sql, "array"); let arr = parseServiceResult(rawResult); renderTable(arr); } catch (e) { console.error("查询失败", e); alert("错误:" + (e.message || e)); } finally { window.__isQuerying = false; } } /** * 安全解析 service 返回的结果 * 支持:合法JSON / 非法JSON / JS数组字面量 / 字符串化数组 / null等 */ function parseServiceResult(rawResult) { console.log("【原始返回类型】", typeof rawResult); console.log("【原始内容】", rawResult); // 情况1:已经是数组 if (Array.isArray(rawResult)) { console.log("✅ 已识别为原生数组"); return rawResult; } // 情况2:null/undefined/false if (rawResult == null || rawResult === 'null' || rawResult === 'undefined') { console.warn("⚠️ 返回为空值"); return []; } // 转为字符串处理 let str = String(rawResult).trim(); if (!str) { console.warn("⚠️ 返回空字符串"); return []; } // 情况3:可能是HTML错误页(常见于服务异常) if (str.startsWith('<') || str.includes('<html') || str.toLowerCase().includes('error') || str.includes('Exception')) { console.error("🔴 返回了HTML错误页!", str.substring(0, 200)); throw new Error('服务端错误,请检查SQL语法或联系管理员'); } /** * 数据清洗函数:修复各种非法字符 */ function clean(str) { return str .replace(/\\\\/g, '\\') // 修复多个反斜杠 .replace(/"/g, '\\"') // 先转义双引号 .replace(/'/g, '"') // 单引号 → 双引号 .replace(/\\"/g, '"') // 还原正常引号 .replace(/\\n/g, '\\n') // 显式换行 .replace(/\\r/g, '\\r') .replace(/\\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/\t/g, '\\t') .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, '') // 移除控制字符 .replace(/^"(\[.*\])"$/, '$1') // 去掉 "[...]" 外层引号 .replace(/^"(\{.*\})"$/, '$1') .replace(/,\s*}/g, '}') // 去除对象尾部逗号 .replace(/,\s*]/g, ']'); // 去除数组尾部逗号 } // 尝试多种解析方式 const parsers = [ // 方式1:直接JSON.parse () => JSON.parse(str), // 方式2:清洗后再解析 () => JSON.parse(clean(str)), // 方式3:作为JS表达式执行(仅限可信环境) () => new Function(`return (${str});`)(), // 方式4:进一步清理后尝试 () => JSON.parse(clean(str).replace(/""/g, '"').replace(/"\s+:/g, '":').replace(/:\s+"/g, ':"')) ]; for (let i = 0; i < parsers.length; i++) { try { const result = parsers[i](); if (Array.isArray(result)) { console.log(`✅ 第 ${i+1} 种方式解析成功`); return result; } // 兼容 { data: [...] } 结构 if (result && Array.isArray(result.data)) return result.data; if (result && Array.isArray(result.rows)) return result.rows; } catch (e) { console.warn(`📌 方式 ${i+1} 解析失败`, e.message); } } // 情况5:手动解析简单二维数组字符串 [[...],[...]] if (/^\[\s*$$[^$$]*$\s*(,\s*$$[^$$]*$)*\s*\]$/.test(str)) { try { console.log("🔍 检测到疑似二维数组字符串,尝试手动解析"); const rows = str.match(/$[^$$]*$/g) || []; return rows.map(row => { return row.replace(/^\[/, '').replace(/\]$/, '') .split(',') .map(field => field.trim().replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1')); }).filter(r => r.length > 0); } catch (e) { console.error("手动解析失败", e); } } // 所有方式都失败 console.error("🔴 所有解析方式均失败", { raw: rawResult, cleaned: clean(str) }); throw new Error('返回数据格式异常,无法解析。请检查SQL是否正确或联系开发人员。'); } /** * 渲染查询结果为表格 */ function renderTable(arr) { var container = document.getElementById("resultTableContainer"); if (!container) return; // 清空容器 container.innerHTML = ''; if (!arr || arr.length === 0) { container.innerHTML = ` <p style="text-align:center;color:#999;font-style:italic;padding:20px;"> 📭 未找到匹配的数据。 </p> `; return; } // 创建表格 var table = document.createElement('table'); table.className = 'tableListBorder'; table.style.width = '100%'; table.style.tableLayout = 'fixed'; table.setAttribute('border', '1'); table.setAttribute('cellpadding', '6'); table.setAttribute('cellspacing', '0'); table.style.fontFamily = 'Arial, sans-serif'; table.style.fontSize = '13px'; // 表头 var thead = document.createElement('thead'); var headerRow = document.createElement('tr'); var headers = [ "Subject", "Status", "申请人", "申请日期", "产品类别", "其他", "类型", "内勤", "系统", "客户", "项目名称", "装置名称", "新产品", "E-NO/序列号", "目标价", "数量", "产地", "含税报价", "处理备注", "备注", "描述" ]; headers.forEach(function(text) { var th = document.createElement('th'); th.style.backgroundColor = '#f5f5f5'; th.style.textAlign = 'center'; th.style.padding = '10px'; th.style.whiteSpace = 'nowrap'; th.style.fontWeight = 'bold'; th.textContent = text; headerRow.appendChild(th); }); thead.appendChild(headerRow); table.appendChild(thead); // 表体 var tbody = document.createElement('tbody'); arr.forEach(function(row, index) { if (!row || !Array.isArray(row) && typeof row !== 'object') { console.warn(`第 ${index} 行数据异常`, row); return; } var tr = document.createElement('tr'); Object.values(row).forEach(function(cell) { var td = document.createElement('td'); td.style.padding = '8px'; td.style.borderTop = '1px solid #eee'; td.style.wordBreak = 'break-word'; td.style.maxWidth = '200px'; td.textContent = cell == null ? '' : String(cell).trim(); tr.appendChild(td); }); tbody.appendChild(tr); }); table.appendChild(tbody); container.appendChild(table); console.log(`✅ 成功渲染 ${arr.length} 行数据`); } </script> <div id="resultTableContainer" style="margin-top: 20px; overflow-x: auto;"> </div> 完整修复以上 [ENO序列号] 匹配问题 数值不能完全匹配
最新发布
10-22
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值