gpt4 book ai didi

sql - 如果我在 SQL 查询中调用一个函数,它会在每一行上进行评估吗?

转载 作者:行者123 更新时间:2023-12-04 13:51:33 25 4
gpt4 key购买 nike

我有一系列常量函数来简化一些 SQL 查询的编程和阅读。例如,

dbo.CONST_DogBreed(NVARCHAR(MAX)) 将为给定的犬种返回 INT。例如,dbo.CONST_DogBreed('Labrador') 可能会返回 12

我的问题是,如果我在查询中用常量调用这个函数,它会重复计算它还是会意识到它是一个常量而只计算一次?所以,如果我要这样做:

SELECT * FROM Dogs
WHERE [DogType] = dbo.CONST_DogBreed('Labrador')

它会每次都评估 dbo.CONST_DogBreed('Labrador') 吗?我意识到这里的解决方案是在上面的变量中声明我想要的值,但如果没有必要,我宁愿不这样做。

即必须在每个查询的顶部执行此操作:

DECLARE @LabradorBreed INT = dbo.CONST_DogBreed('Labrador');
SELECT * FROM Dogs
WHERE [DogBreed] = @LabradorBreed

在写这个问题时经过一些研究,似乎它可能基于函数是否是确定性的。如果是这样,我如何确保我的函数是确定性的?它会为我做吗?有几个指定确定性的 sql 问题和其他一些使用模式绑定(bind)之类的问题。因为我的 const 函数不使用任何模式,所以我认为模式绑定(bind)是不必要的。

所以我想在这项研究之后归结为:我如何确保我的函数是确定性的?

最佳答案

The Database Engine automatically analyzes the body of Transact-SQL functions and evaluates whether the function is deterministic. For example, if the function calls other functions that are non-deterministic, or if the function calls extended stored procedures, then the Database Engine marks the function as non-deterministic. For common language runtime (CLR) functions, the Database Engine relies on the author of the function to mark the function as deterministic or not using the SqlFunction custom attribute.

...

you need to add WITH SCHEMABINDING to the header of a user defined function in order to make it applicable for a "Deterministic" label.

https://technet.microsoft.com/en-us/library/ms187440(v=sql.105).aspx

关于sql - 如果我在 SQL 查询中调用一个函数,它会在每一行上进行评估吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41248897/

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