1. 程式人生 > >sql的轉義字元單引號

sql的轉義字元單引號

在SQL中,我們都知道單引號 ' 表示字串的開始和結束符號,如:

select * from students where name = '小明';

但如果字串裡面有單引號時,應該怎麼查詢呢?

這是我最近遇到的一個問題,需求是對一張表的資料進行更新,但各個環境的資料並不一致,只能通過拼接的方式生成適合對應環境的變更指令碼。更新語句格式如下:

1 update students set grade = '一年級' where grade_id = '01' and grade is null;
2 update students set grade = '二年級' where
grade_id = '02' and grade is null; 3 ... 4 --只是舉例,實際就是各個環境欄位值不一致,需要先根據環境拼接變更指令碼

拼接sql語句的指令碼初始如下:

--db2資料庫使用下面的語句
select 'update students set grade = ' || grade || ' where grade_id = ' || grade_id || ' and grade is null;' from classes
where grade_id in (select grade_id from students where grade_id is
not null and grade is null); --mysql資料庫使用下面的語句 select concat('update students set grade = ',grade,' where grade_id = ',grade_id,' and grade is null;') from classes where grade_id in (select grade_id from students where grade_id is not null and grade is null);

 結果如下:

可以發現,字串值沒有單引號,直接執行會報錯。google後找到解決辦法。

sql單引號

sql的轉義字元單引號 ' ,可以對字串中的單引號進行轉義,使其表示字串值 ' ,這樣如果要查詢 name 為 小'明 的值,其sql語句如下:

select * from students where name = '''';

所以上面的拼接指令碼修改如下,即可生成正確的update語句。

1 --db2資料庫使用下面的語句
2 select 'update students set grade = ''' || grade || ''' where grade_id = ''' || grade_id || ''' and grade is null;' from classes
3 where grade_id in (select grade_id from students where grade_id is not null and grade is null);
4 
5 --mysql資料庫使用下面的語句
6 select concat('update students set grade = ''',grade,''' where grade_id = ''',grade_id,''' and grade is null;') from classes 
7 where grade_id in (select grade_id from students where grade_id is not null and grade is null);
8 
9 --注意三個逗號需連續,且與其他字元間的空格