我將二進制資料存盤在需要在多行中的 Postgres 資料庫中。為了不使用相同的文本污染我的設定 sql 檔案,我試圖定義一個常量,然后在 INSERT 陳述句中使用該常量。我目前正在嘗試這樣的事情
-- my_data.sql
SET my_binary_file = '\x232120433a2f50726f6772616d2046696c...';
INSERT INTO public."MyTable" VALUES (1, :'my_binary_file')
然后使用 psql -f my_data.sql
但這只會導致
ERROR: syntax error at or near ":"
我已經看到使用 psql 命令列完成了許多類似的事情,但沒有一個作業。
uj5u.com熱心網友回復:
您需要使用會話變數并使用函式 current_setting() 訪問變數中的值。
像這樣:
postgres=# create table MyTable(id int, my_binary_file varchar(1000));
CREATE TABLE
postgres=# \! cat my_data.sql
set session my.my_binary_file = '\x232120433a2f50726f6772616d2046696c...';
insert into MyTable values(1,current_setting('my.my_binary_file'));
postgres=#
postgres=# truncate table MyTable;
TRUNCATE TABLE
postgres=# select * from MyTable;
id | my_binary_file
---- ----------------
(0 rows)
postgres=# \i my_data.sql
SET
INSERT 0 1
postgres=# select * from MyTable;
id | my_binary_file
---- -----------------------------------------
1 | \x232120433a2f50726f6772616d2046696c...
(1 row)
uj5u.com熱心網友回復:
你不能在 SQL 中使用變數,你需要 PL/pgSQL。您可以使用DO塊。
DO
$$
DECLARE
my_binary_file bytea = '\x232120433a2f50726f6772616d2046696c';
BEGIN
INSERT INTO mytable
VALUES (1,
my_binary_file);
END;
$$
db<>小提琴
并建議作為旁注:不要使用帶引號的識別符號,例如區分大小寫的表名。歸根結底,它只會讓你頭疼。表名不需要“漂亮”。
uj5u.com熱心網友回復:
您可以定義自己的配置引數,請參閱手冊:
SELECT set_config('myvar.my_binary_file', '\x232120433a2f50726f6772616d2046696c...', false) ;
INSERT INTO public."MyTable" VALUES (1, current_setting('myvar.my_binary_file')) ;
dbfiddle中的測驗結果。
uj5u.com熱心網友回復:
您似乎將psql變數與其他形式混合在一起。psql 反斜杠命令明確不應該是 SQL,并且如果您通過 python 腳本等運行腳本將不起作用,但只能使用 psql。
所以 - 話雖如此,您可以輕松地做到這一點 - 您只需要正確參考該值。psql 變數只是剪切和粘貼樣式的宏,因此確切的文本將嵌入到查詢字串中。
\set my_binary_file $$'\x232120433a2f50726f6772616d2046696c...'$$
INSERT INTO "MyTable" VALUES (1, :my_binary_file);
請注意我們如何需要對變數的值進行雙引號,因為在嵌入的位置沒有引號。為此使用 PostgreSQL 的美元報價似乎是最簡單的。還要注意缺少分號\set- 這不是 SQL 陳述句,它都需要放在一行中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/413579.html
標籤:
