zoukankan      html  css  js  c++  java
  • 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 --注意三个逗号需连续,且与其他字符间的空格
     
    如: insert into yourTable(f1,f2) values(100,'ab''c') 可以插入   ab'c
     
  • 相关阅读:
    python dict
    用Python requests beautifulSoup 获取并显示中文信息
    Python information to learn
    Python 中的异常
    Python 中的函数
    安装Linux系统Fedora 23
    (转)开源协议的比较
    WizNote for linux installation
    linux下编译bib、tex生成pdf文件
    NLP学术组织、会与论文
  • 原文地址:https://www.cnblogs.com/sunny3158/p/11598155.html
Copyright © 2011-2022 走看看