关于Oracle字符拼接的一些东西

来源:互联网 发布:获取数组的长度 编辑:程序博客网 时间:2024/06/03 12:45

表一 :人员表person

      ID           姓               名字        

      1            张                 三

      2            李                 四

      3            王                 五

表二:人员兴趣表person_hobby

    PId              HId

    1                   1

    1                   2

    1                   3

    2                   2

    2                   3

表三:兴趣表hobby

     ID                detial

     1                  唱歌

     2                  游泳

     3                  足球

(1)查询人员表,要求显示姓名连接在一起 如:

    ID            全名

    1              张三

操作:首先采取直接拼接的方式  CONCAT(arg1,arg2)函数

select  ID,CONCAT(姓,名字) as 全名 from person

或者 采取"||"连接符

select  ID,(姓||名字)  as  全名 from person

在用“||” 连接符时还可以加上你需要的东西    如  select  ID,(姓||‘-’||名字)  as  全名 from person 

而且 在用CONCAT函数时只能连接两个参数,但是用"||"连接符可以连接任意个参数


(2)要求查询人员信息,同时显示该人员的兴趣爱好 要求显示格式如下:

     ID               name                 hobby

     1                 张三              唱歌,游泳,足球

   需要先写一个函数my_concat()


create or replace function my_concat(mid in integer) return varchar2       --记住:参数和返回值里的数据类型都不用定义长度      
is     
result varchar2(4000);    --定义变量,记住Oracle中定义变量不需要      
begin     
       for temp_cursor in (select temp1.detial from hobby temp1,person_hobby  temp2 where temp1.ID = temp2.HId  and temp2.PId=mid) loop  

            --此处在游标FOR循环中使用查询      
           result :=result || temp_cursor.detial || ',';    --Oracle中字符连接使用||,而sql server中用+             
       end loop;      
       result := rtrim(result,',');  --去掉最后一个空格,还有Oracle中的赋值前面没有set      
       return result;      
end;  


查询语句为:

select ID,CONCAT(姓,名字) as name, my_concat(ID) as hobby from person

 




原创粉丝点击