24 / 12 / 12

SuiteQL #001:入门指南

1 什么是 SuiteQL

SuiteQL 是一种基于 SQL 数据库查询语言的 SQL-92 修订版的查询语言

2 如何运行 SuiteQL

有 2 种方法可以运行 SuiteQL 查询,分别是 SuiteScript 的N/query 模块和SuiteTalk REST Web Service。

2.1 SuiteScript

使用N/query 模块的 query.runSuiteQL() 函数运行 SuiteQL。
代码示例:

function queryTransData() { const sqlStatement = `SELECT transaction.tranid, transaction.trandate from transaction where rownum < 10`; const queryObj = query.runSuiteQL(sqlStatement); const results = queryObj.asMappedResults(); log.debug('results', results); }

输出示例:

[ { tranid: 'SO001', trandate: '2024/01/01' }, { tranid: 'SO002', trandate: '2024/01/02' }, { tranid: 'SO003', trandate: '2024/01/03' }, { tranid: 'SO004', trandate: '2024/01/04' } ]

2.2 SuiteTalk REST Web Service

通过 REST Web Serveice 执行 SuiteQL 查询

  • URL:https://{accountId}.suitetalk.api.netsuite.com/services/rest/query/v1/suiteql{accountId}是账户 ID,查看路径:设置 > 公司 > 公司信息

  • 请求方式:POST

  • 请求体:{ "q" : queryStatement },其中 queryStatement 为查询语句

代码示例:

curl -i -X POST 'https://{accountId}.suitetalk.api.netsuite.com/services/rest/query/v1/suiteql' \ -H 'Content-Type: application/json' \ -H 'Authorization: *******************************' \ -d { "q" : "SELECT transaction.tranid, transaction.trandate from transaction where rownum < 10"}

响应示例:

{ "links": [ { "rel": "self", "href": "https://{accountId}.suitetalk.api.netsuite.com/services/rest/query/v1/suiteql" } ], "count": 4, "hasMore": false, "items": [ { "links": [], "tranid": "SO001", "trandate": "2024/01/01", "id": "221" }, { "links": [], "tranid": "SO002", "trandate": "2024/01/02", "id": "222" }, { "links": [], "tranid": "SO003", "trandate": "2024/01/03", "id": "223" }, { "links": [], "tranid": "SO004", "trandate": "2024/01/04", "id": "224" } ], "offset": 0, "totalResults": 4 }

3 SuiteQL 表结构

NetSuite 没有提供明确的表结构,常见的表有事务处理、事务处理行、实体等。虽然没有明确的表结构,但我们可以使用记录目录来查阅常见表及其字段信息。路径:设置 >> 记录目录

4 SuiteQL 语法&传参

SuiteQL 支持 SQL-92 和 Oracle SQL 的语法,但不能在同一查询中使用这两种语法。以下为语法参考:

SuiteQL 传参有两种方式:

  1. SuiteQL 支持动态性参数
    在查询语句中使用问号替代参数,然后将参数数组传递给 runSuiteQL 函数
function getTransactionsByType(type) { const queryObj = query.runSuiteQL(`SELECT transaction.tranid, transaction.trandate from transaction where type = ? and rownum < 10`, [type]) const results = queryObj.asMappedResults(); log.debug('results', results); } // 销售订单 getTransactionsByType('SalesOrd'); // 发票 getTransactionsByType('CustInvc')
  1. 使用字符串拼接
function getTransactionsByType(type) { const queryObj = query.runSuiteQL(`SELECT transaction.tranid, transaction.trandate from transaction where type = '${type}' and rownum < 10`) const results = queryObj.asMappedResults(); log.debug('results', results); } // 销售订单 getTransactionsByType('SalesOrd'); // 发票 getTransactionsByType('CustInvc')

5 优缺点

在 SuiteQL 未出现之前,我们使用已保存搜索查询数据,那 SuiteQL 与已保存搜索相比有哪些优缺点呢?

优点:

  1. 数据查询速度更快

  2. 多表关联

缺点:

  1. 无法在 UI 中使用

  2. 语法相对复杂,学习成本较高

Powered by Gridea