在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 –注意三个逗号需连续,且与其他字符间的空格
如: insert into yourTable(f1,f2) values(100,’ab”c’) 可以插入 ab’c
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/220791.html原文链接:https://javaforall.net
