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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM