gpt4 book ai didi

sql - 表函数中的条件 UNION ALL

转载 作者:行者123 更新时间:2023-12-02 06:35:31 28 4
gpt4 key购买 nike

所以用例如下 - 有一些参数,我想根据这些参数从一个表或另一个表中选择数据。

create table dbo.TEST1 (id int primary key, name nvarchar(128))
create table dbo.TEST2 (id int primary key, name nvarchar(128))

所以我创建了这样的函数:

create function [dbo].[f_TEST]
(
@test bit
)
returns table
as
return (
select id, name from TEST1 where @test = 1

union all

select id, name from TEST2 where @test = 0
)

当我使用常量运行它时,执行计划很棒 - 只扫描一个表

select * from dbo.f_TEST(1)

enter image description here

但是,当我使用变量时,计划并不是那么好 - 两个表都被扫描

declare @test bit = 1

select * from dbo.f_TEST(@test)

enter image description here

那么有没有什么提示(或技巧)可以强制 SQL Server 理解在某个查询中只应该扫描一个表?

最佳答案

如果您的函数是内联 TVP(如示例所示),那么您可以使用:

declare @test bit = 1
select * from dbo.f_TEST(@test) OPTION (RECOMPILE);

然后在这两种情况下,您都将获得单个聚集索引扫描。

<强> DBFiddle Demo

来自Option RECOMPILE :

When compiling query plans, the RECOMPILE query hint uses the current values of any local variables in the query and, if the query is inside a stored procedure, the current values passed to any parameters.

关于sql - 表函数中的条件 UNION ALL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45699617/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com