zoukankan      html  css  js  c++  java
  • SQL SERVER 字符串操作注意点

      有一张新闻数据表tb_news,该表有字段news_id int, news_type int,前者是主键,后者是新闻所属栏目ID,现在要求是这样:

    给定一个字符串a_right,该字符串中包含多个新闻栏目ID值,即news_type,并且存储格式是'b'+news_type+'v',各ID值之间以逗号相隔,

    例如:b1v, b2v, b3v……

      现在要从新闻表中查询出所有news_type经格式转换为'b'+news_type+'v'后,该格式的新闻栏目被包含在a_right中的新闻,刚

    开始写的查询语句如下:

      select * from tb_news where charindex('b'+str(news_type)+'v', @a_right) >= 1

      结果执行结果与愿望中的结果大相径庭!

      经过反复排查,最后终于查出原因所在:SQL SERVER的str()函数有两个参数:str(express, length),当未指定length时,默认

    是转为字符串后,字符串左边保留10个空字符,例如:print 'b'+str(2),则结果为b          2。因此,需要将转化后的字符串去掉空值,

    此时可以使用ltrim()函数,例如执行:print 'b'+ltrim(str(2)),结果为b2。

      于是将上面的查询语句改为:

      select * from tb_news where charindex('b'+ltrim(str(news_type))+'v', @a_right) >= 1

      顺利执行!

      附:

      一 str函数详解

      在SQL SERVER Manage Studio中执行:

      print 'b'+str(333, 1) 结果为:b3;

      print 'b'+str(333, 2) 结果为:b33;

      print 'b'+str(333, 4) 结果为:b*;

      print 'b'+str(333)    结果为:b          333

      二 SQL SERVER中针对字符串操作的函数有如下几个常用:

      1.1 长度与分析用  

      datalength(Char_expr) 返回字符串包含字符数,但不包含后面的空格 

      substring(expression,start,length) 不多说了,取子串 

      right(char_expr,int_expr) 返回字符串右边int_expr个字符  

      1.2 字符操作类  

      upper(char_expr) 转为大写 

      lower(char_expr) 转为小写

      space(int_expr) 生成int_expr个空格

      replicate(char_expr,int_expr)复制字符串int_expr次

      reverse(char_expr) 反转字符串

      stuff(char_expr1,start,length,char_expr2) 将字符串char_expr1中的从start开始的length个字符用char_expr2代替 

      ltrim(char_expr) 去掉左边的空格;rtrim(char_expr) 去掉右边的空格

      ascii(char) char(ascii) 两函数对应,取ascii码,根据ascii吗取字符  

      1.3 字符串查找

      charindex(char_expr,expression) 返回char_expr的起始位置;索引从数字1开始,而非0

      patindex("%pattern%",expression) 返回指定模式的起始位置,否则为0  

  • 相关阅读:
    〖Linux〗Kubuntu设置打开应用时就只在打开时的工作区显示
    〖Linux〗Kubuntu, the application 'Google Chrome' has requested to open the wallet 'kdewallet'解决方法
    unity, dll is not allowed to be included or could not be found
    android check box 自定义图片
    unity, ios skin crash
    unity, Collider2D.bounds的一个坑
    unity, ContentSizeFitter立即生效
    类里的通用成员函数应声明为static
    unity, Gizmos.DrawMesh一个坑
    直线切割凹多边形
  • 原文地址:https://www.cnblogs.com/pricks/p/1703292.html
Copyright © 2011-2022 走看看