在 Oracle 資料庫中,單引號 (') 是字串常數的界定符號。若欲將包含單引號的字串寫入資料表,必須進行轉義處理,否則會導致 SQL 語法錯誤。最常見的方法是將單引號加倍(即寫成兩個連續單引號 '')。
INSERT INTO Tai_Kpi_src (kpi_id, kpi_name, v_sql)
VALUES (
4,
'test',
'select to_char(a.start_time time,''yyyy-mm-dd hh24:mi:ss'', a.hw_sys_calls_r value
from tpm_rt_msc_call_ss_h a
where exists (select 1 from a_objects b
where a.int_id = b.int_id
and b.object_class = 101
and b.tmsc_cat = 0
and b.vendor_id = 8
and b.confirmed < 2
and #ne_id#)
and a.start_time >= to_date(''#start_time#'', ''yyyy-mm-dd hh24:mi:ss'')
and a.start_time < to_date(''#stop_time#'', ''yyyy-mm-dd hh24:mi:ss'')
and a.hw_sys_calls_r is not null'
);
執行後,v_sql 欄位實際儲存的值會將雙單引號還原為單引號:
select to_char(a.start_time time,'yyyy-mm-dd hh24:mi:ss', a.hw_sys_calls_r value
from tpm_rt_msc_call_ss_h a
where exists (select 1 from a_objects b
where a.int_id = b.int_id
and b.object_class = 101
and b.tmsc_cat = 0
and b.vendor_id = 8
and b.confirmed < 2
and #ne_id#)
and a.start_time >= to_date('#start_time#', 'yyyy-mm-dd hh24:mi:ss')
and a.start_time < to_date('#stop_time#', 'yyyy-mm-dd hh24:mi:ss')
and a.hw_sys_calls_r is not null
若要插入的字串本身含有單引號,例如 123'34'5,則寫成:
INSERT INTO tb_name (column_name) VALUES ('123''''34''''5');
說明:每個原始單引號在 SQL 字串常數中以兩個單引號表示,因此 ' 變為 '',若原字串有兩個單引號,則各自加倍,形成四個單引號連續出現。
Oracle 10g 引入 q'[...]' 語法,可自訂分隔符號,避免大量轉義:
INSERT INTO tb_name (col) VALUES (q'[123'34'5]');
這在處理包含大量引號的動態 SQL 時更為清晰易維護。