这是我的第452篇文章,写于2021年08月03日。
首先我们来看Web API查询,如果不需要进行特殊处理的话,类似的查询如下:
var accountName = "A. Datum Corporation (sample)";
var queryExp = `$filter=name eq '${accountName}'`;
Xrm.WebApi.retrieveMultipleRecords("account", `?$select=name&${queryExp}&$top=1`).then(
function success(result) {
for (var i = 0; i < result.entities.length; i++) {
console.log(result.entities[i]);
}
},
function (error) {
console.log(error.message);
}
);
上面的查询没有问题,但是如果要查询的account的name包括了特殊字符,比如英文输入法下的单引号如何处理呢?比如下面的查询会报错:
Syntax error at position 30 in 'name eq 'A. Datum' Corporation (sample)''
var accountName = "A. Datum' Corporation (sample)";
var queryExp = `$filter=name eq '${accountName}'`;
Xrm.WebApi.retrieveMultipleRecords("account", `?$select=name&${queryExp}&$top=1`).then(
function success(result) {
for (var i = 0; i < result.entities.length; i++) {
console.log(result.entities[i]);
}
},
function (error) {
console.log(error.message);
}
);
如何解决呢?解决办法就是将单引号替换成两个单引号,如下:
function encodeQueryStr(queryStr) {
if (queryStr) {
return queryStr.replace("'", "''");
}
else {
return "";
}
}
var accountName = "A. Datum' Corporation (sample)";
var queryExp = `$filter=name eq '${encodeQueryStr(accountName)}'`;
Xrm.WebApi.retrieveMultipleRecords("account", `?$select=name&${queryExp}&$top=1`).then(
function success(result) {
for (var i = 0; i < result.entities.length; i++) {
console.log(result.entities[i]);
}
},
function (error) {
console.log(error.message);
}
);
那你可能会问还有别的特殊字符需要替换吗?双引号算不算?答案是双引号不用替换。还有其他的吗?我尝试了一些我认为可能需要处理的字符找到如下需要处理的,写成了函数:
function encodeQueryStr(queryStr) {
if (queryStr) {
return queryStr.replace("'", "''").replace("&", "%26").replace("+","%2B");
}
else {
return "";
}
}
对于一些特殊的查询操作符,也就是下列的查询操作符
contains
not contains
startswith
not startswith
endswith
notendswith
下面这些字符有特殊含义,需要进行转义:
Characters | Description | T-SQL Documentation and examples |
| Matches any string of zero or more characters. This wildcard character can be used as either a prefix or a suffix. | Percent character (Wildcard - Character(s) to Match) (Transact-SQL) |
| Use the underscore character to match any single character in a string comparison operation that involves pattern matching. | |
| Matches any single character within the specified range or set that is specified between brackets. | |
| Matches any single character that is not within the range or set specified between the square brackets. |
如何转义请参考 Using Wildcard Characters As Literals ,基本就是用 [] 将这个字符(比如 [, % ,_ 等字符)包括起来,更多信息请参考官方文档:Use wildcard characters in conditions for string values 。
值得注意的是,如果是Flow中使用Microsoft Dataverse这个Connector中的List rows使用Filter来查询数据的时候,不要处理前面文中提到的特殊字符 + 和 & ,但是单引号还是需要替换为两个单引号。
官方文档 Filter rows using OData 的 URL encode special characters 章节提到了在对字符类型字段进行查询时候下面这些字符需要转义:
Special character | URL encoded character |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|