zoukankan      html  css  js  c++  java
  • Sql Server的Cross Apply用法

    apply有两种形式: cross apply 和 outer apply

    区别在于指定OUTER,意味着结果集中将包含使右表表达式为空的左表表达式中的行

    而指定CROSS,则相反,结果集中不包含使右表表达式为空的左表表达式中的行。

    零、cross apply的原理:

    <left_table>  {cross|outer} apply <right_table>

    它是先得出右表里的数据,然后把此数据一条一条的放入左表表式中,分别得出结果集,最后把结果集整合到一起就是最终的返回结果集了

    详解:(拆分后的数据 ,像for循环一样 ,一条一条的进入到left表中, 然后返回一个集合 ,最后把所有的集合整合到一块  就是最终的结果

    一、split 后显示列表数据

    --值班表  split 后列表
    select *from  (select MineOnDuty  from LeaderOnDutyDayReport where LEFT(DayDate,7)='2021-09' ) AS t 
    CROSS APPLY dbo.SplitString( t.MineOnDuty, '',1) AS fs  

    二、split 后统计数据

    --值班表 split 后统计数据
    select Value Leader,count(1) NumZB from  (select MineOnDuty  from LeaderOnDutyDayReport where LEFT(DayDate,7)='2021-09' ) AS t 
    CROSS APPLY dbo.SplitString( t.MineOnDuty, '',1) AS fs  group by Value

     三、SplitString函数

    该函数用于将数据库中字符串根据特定字符进行分割成数组,SQL中无split函数,该函数实现的就是C#程序中split功能。

    select * from SplitString("需要拆分字符串", '特定字符',1)

    Create function [dbo].[SplitString]
    (
        @Input nvarchar(max),
        @Separator nvarchar(max)=',', 
        @RemoveEmptyEntries bit=1 
    )
    returns @TABLE table 
    (
        [Id] int identity(1,1),
        [Value] nvarchar(max)
    ) 
    as
    begin 
        declare @Index int, @Entry nvarchar(max)
        set @Index = charindex(@Separator,@Input)
    
        while (@Index>0)
        begin
            set @Entry=ltrim(rtrim(substring(@Input, 1, @Index-1)))
            
            if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'')
                begin
                    insert into @TABLE([Value]) Values(@Entry)
                end
    
            set @Input = substring(@Input, @Index+datalength(@Separator)/2, len(@Input))
            set @Index = charindex(@Separator, @Input)
        end
        
        set @Entry=ltrim(rtrim(@Input))
        if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'')
            begin
                insert into @TABLE([Value]) Values(@Entry)
            end
    
        return
    end
  • 相关阅读:
    Linux_C_C++
    01玩转数据结构_09_线段树Segment Tree(区间树)
    线性代数
    概率与统计
    矩阵快速幂—— 构造矩阵
    2020百度之星程序设计大赛复赛
    Codeforces Round #662 (Div. 2)
    2020百度之星程序设计大赛初赛二
    2020百度之星程序设计大赛初赛一
    安全参考监视器支持例程(转的微软的)
  • 原文地址:https://www.cnblogs.com/MirZhai/p/15269963.html
Copyright © 2011-2022 走看看