zoukankan      html  css  js  c++  java
  • cross apply 和 outer apply

    使用APPLY运算符可以实现查询操作的外部表表达式返回的每个调用表值函数。表值函数作为右输入,外部表表达式作为左输入。

    通过对右输入求值来获得左输入每一行的计算结果,生成的行被组合起来作为最终输出。APPLY 运算符生成的列的列表是左输入

    中的列集,后跟右输入返回的列的列表。

    APPLY存在两种形式: CROSS APPLY 和 OUTER APPLY .

    CROSS APPLY 仅返回外部表中通过表值函数生成结果集的行。

    OUTER APPLY 既返回生成结果集的行,又返回不生成结果集的行,其中表值函数生成的列中的值为NULL.



    create table employee
    (
    emp_id int not null,
    mgr_id int null,
    emp_name varchar(20) not null,
    emp_salary money not null,
    constraint pk_id primary key(emp_id)
    )

    insert into employee select 1,null,'忘忘',4500
    union all
    select 2,1,'找找',2500
    union all
    select 3,2,'你会',3500
    union all
    select 4,3,'牛牛',1500
    union all
    select 5,4,'得到',500
    union all
    select 6,5,'爱的色放',300
    union all
    select 7,6,'爱上对方',1000
    union all
    select 8,4,'阿萨德',300
    union all
    select 9,8,'阿斯顿',1000

    create table departments
    (
    dep_id int identity(1,1) primary key,
    dep_name varchar(30) not null,
    dep_m_id int null references employee(emp_id)
    )
    insert departments select '生成部门',2
    union all
    select '销售部门',7
    union all
    select '加工部门',8
    union all
    select '库存部门',9
    union all
    select '管理部门',4
    union all
    select '保卫部门',null

    create function gtree
    (
    @emp_id int
    )
    returns @tree table
    (
    emp_id int not null,
    emp_name varchar(20) not null,
    mgr_id int null,
    lvl int not null
    )
    as
    begin
    with emp_subtree(emp_id,emp_name,mgr_id,lvl)
    as
    (
    select emp_id,emp_name,mgr_id,0 from employee where emp_id=@emp_id
    union all
    select e.emp_id,e.emp_name,e.mgr_id,es.lvl+1
    from employee e join emp_subtree es on e.emp_id=es.emp_id
    )
    insert @tree select * from emp_subtree
    return
    end
    select * from employee

    select * from departments as a
    cross apply
    gtree(a.dep_m_id) as b

    select * from departments as a
    outer apply
    gtree(a.dep_m_id) as b

  • 相关阅读:
    Linux/Android 系统怎么修改mac地址
    Vue.js和jQuery混合使用的一点注意事项
    wpf研究之道——datagrid控件及样式
    asp.net url重写
    如何解决一个问题
    Word 2007 封面、目录和正文页码单独设置
    .net 多线程
    我对asp.net运行机制的理解
    Firefox扩展安装
    谷歌chrome 插件(扩展)开发——谈谈安装
  • 原文地址:https://www.cnblogs.com/accumulater/p/6158574.html
Copyright © 2011-2022 走看看