首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> Oracle 資料庫 >> Oracle 資料庫基礎

Oracle 資料庫插入單引號的正確處理方式

     編輯:Oracle 資料庫基礎

Oracle 中單引號的轉義技巧

在 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 字串常數中以兩個單引號表示,因此 ' 變為 '',若原字串有兩個單引號,則各自加倍,形成四個單引號連續出現。

替代方案:使用 q 引用符號 (Oracle 10g+)

Oracle 10g 引入 q'[...]' 語法,可自訂分隔符號,避免大量轉義:

INSERT INTO tb_name (col) VALUES (q'[123'34'5]');

這在處理包含大量引號的動態 SQL 時更為清晰易維護。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved