簡體   English   中英

如何將間隔參數傳遞給准備好的語句?

[英]How to pass an interval parameter to a prepared statement?

我想刪除我的 Postgres 數據庫中早於 X 分鍾的所有數據庫條目。 我在 go 中准備好的語句如下所示:

delete
from my_table
where expires < (to_timestamp($1) - '$2 minutes'::interval);

如何正確傳遞第二個參數$2


PS:我知道有不同的語句可以解決這個問題,但我對如何傳遞引用的參數很感興趣。

您可以參數轉換為text ,然后將其與字符串' minutes' 連接起來。

delete from my_table
where expires < (to_timestamp($1) - ($2::text || ' minutes')::interval

更新:實際上,因為 postgres 確實有一個any || text any || text運算符,其結果是text ,您不需要鍵入參數。

無法將參數插入字符串文字。

您的情況的可能解決方案是將一個數字乘以一個間隔:

where expires < (to_timestamp($1) - $2 * '1 minute'::interval)

你可以使用make_interval

delete from my_table
where expires < (to_timestamp($1) - make_interval(mins => $2));

您也可以參數化整個間隔字符串。 這消除了對text和連接的中間轉換的需要。

query := `
  delete from my_table
  where expires < (to_timestamp($1) - $2::interval);
`
interval := fmt.Sprintf("%d minutes", mins)
db.Exec(query, timestamp, interval)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM