sql的转义字符单引号

在SQL中,咱们都知道单引号 ' 表示字符串的开始和结束符号,如:html

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

但若是字符串里面有单引号时,应该怎么查询呢?mysql

这是我最近遇到的一个问题,需求是对一张表的数据进行更新,但各个环境的数据并不一致,只能经过拼接的方式生成适合对应环境的变动脚本。更新语句格式以下:sql

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

能够发现,字符串值没有单引号,直接运行会报错。google后找到解决办法。sql单引号spa

sql的转义字符单引号 ' ,能够对字符串中的单引号进行转义,使其表示字符串值 ' ,这样若是要查询 name 为 小'明 的值,其sql语句以下:code

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

因此上面的拼接脚本修改以下,便可生成正确的update语句。htm

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 --注意三个逗号需连续,且与其余字符间的空格

 

原文出处:https://www.cnblogs.com/readerman/p/10213375.htmlblog

相关文章
相关标签/搜索