使用記錄 ID

Ninox 中的記錄 ID

  • Ninox 中每一筆新記錄都會取得一個唯一的 ID(識別碼)。
  • 新表格的編號從 1 開始,每新增一筆就加 1(2、3 等等)。
  • 被刪除的 ID 不會重新配發。因此,表格中最大的 ID 反映的是曾經建立過的記錄總數,包含那些已被刪除、不再看得到的記錄。
  • ID 的表示方式:
    • ID 可以用數字或文字表示。
    • 以文字表示時,ID 由表格的 ID(一個或多個大寫字母)加上記錄編號組成。
      例如:"A1"

關於 ID 的重點

  • 把 ID 轉換成文字:
    • 用 string() 函式取得 ID 的文字表示。
    • text() 函式只會把 ID 的數字部分轉成文字。例如:"1"。
  • 範例:
Ninox
"Correct textual representation, e.g. ""A1""";
string(maTable.id);
"Only the numeric part as text, e.g. ""1""";
text(maTable.id);
  • 在運算式中使用 ID:
    • 進行算術運算或字串串接時,ID 會採用另一項資料的型別。
  • 範例:
Ninox
var t := "Num ID: " + maTable.id;

輸出:Num ID: 1

依 ID 搜尋記錄

若要在 where 子句中依 ID 取得記錄,數字或文字表示皆可使用。

使用數字:

Ninox
select Customer where id = 1;

使用文字:

使用文字時,請確認 ID 同時包含表格的 ID 與記錄編號。

例如:

Ninox
select Customer where id = "B1";

從 ID 中取出記錄編號

這個函式可以從文字形式的 ID(例如 A1)中取出記錄編號:

Ninox
function recordNumber(id : text) do
  "Capture the digit group.";
  number(extractx(id, "^[A-Z]+([0-9]+)$", "", "$1"))
end;

"Example: apply to the current record’s ID";
var numId := recordNumber(string(myId));

string(myId) 把 ID 轉換成文字。

RegExp ^[A-Z]+([0-9]+)$ 的意思是

  • ^[A-Z]+ → 開頭是一個或多個字母,
  • ([0-9]+) → 我們要的數字(捕捉群組 1),
  • $ → 字串結尾。

extractx(..., "", "$1") 只回傳捕捉到的數字。

number(...) 把那串數字轉換成數值。

用 record() 尋找記錄

record(Table, n) 直接傳回編號為 n 的記錄,不必走訪整張表格。編號必須是大於零的整數:

  • 小數(3.5)、零或負數都不會傳回任何內容,也沒有任何提示:Ninox 不會將編號四捨五入;
  • 3.0 可以接受:它等於 3;
  • 文字("3")或清單([3, 4])在撰寫公式時就會被拒絕(「Expression does not return a number」、「Expression returns multiple values」):以文字形式收到的編號須先用 number() 轉換。

這個陷阱常見於計算出來的編號(record(Customer, total / 2),當 total 為奇數時),或從外部收到的編號,例如透過 API。

Ninox
"Found: record number 3";
record(Customer, 3);
"Nothing, and no error: Ninox does not round";
record(Customer, 3.5);
"A number received as text must be converted first";
record(Customer, number("3"));

注意

與任何記錄都不對應的整數(已刪除或尚未建立)並不會傳回「空」:record() 傳回的是指向一筆不存在記錄的參照。因此 if record(Customer, 999999) then 為真,而 if record(Customer, 3.5) then 為假。

要判斷記錄是否存在,請檢查它的 ID:在這兩種情況下它都是空的。

Ninox
var n := 3.5;
if record(Customer, n).id then
  "The record exists"
else
  "No record: n is not a whole number greater than zero, or no record has this number"
end

(透過 API 在一張 8 筆記錄的表格上實測。)