SQL Server 2005 - 交叉应用,tvf和更新/删除

时间:2014-07-28 10:12:23

标签: sql sql-server cross-apply

我怎样才能做出像这样的事情

select 
    a.atest, a.btest, a.ctest, b.atest, b.btest
from 
    test.dbo.rm a(nolock)
cross apply 
    wat.dbo.ar(a.atest,a.btest) b
where 
    a.rmd = 9 and a.btest > 0

alter function ar(@atest varchar(25), @btest numeric(19,5)) 
returns table as 
    return
    (
        select atest, btest from test.dbo.rm (nolock)
        where rmd = 1 and atest=@atest and btest=@btest
    )

使用删除语句或更新。我选择一个b.atest之后我不想复制,我想删除b.atest的记录或将b.btest设置为0.此查询正在包含大约5的表上-10万条记录..所以一定要快。

1 个答案:

答案 0 :(得分:1)

使用不带功能的查询:

select a.atest,a.btest,a.ctest,b.atest,b.btest
from test.dbo.rm a(nolock)
cross apply (
        select top 1 atest, btest 
        from test.dbo.rm t (nolock)
        where t.rmd = 1 and t.atest=a.atest and t.btest=a.btest
        )b
where a.rmd = 9 and a.btest > 0

您也可以使用左连接而不是交叉应用:

select *
from (
    select a.atest,a.btest,a.ctest,b.atest,b.btest,
          row_number() over ( partition by b.atest, b.btest order by b.id) as row
    from test.dbo.rm a(nolock)
    LEFT JOIN test.dbo.rm b ON b.rmd = 1 and b.atest=a.atest and b.btest=a.btest
    where a.rmd = 9 and a.btest > 0
)z
where z.row = 1