0

我写了 sql 查询,在 where 子句中我使用函数来过滤一些行。

我的问题是:我想在选择投影中使用结果函数。我怎么能做这项工作,因为我不喜欢再次调用 dbo.func 来执行?

我的查询是:

Declare @pDate datetime=gatdate()
Select tb1.ID,tb1.Date1,dbo.Func(tb1.Date1,@pDate2)   From tb1 Where 30<=dbo.Func(tb1.Date1,@pDate2)  

谢谢。

4

2 回答 2

1

If you want to avoid using the Func function in select part AND the where part for performance reasons, then you can create a subquery like the following

DECLARE @pDate DATETIME = GETDATE()
SELECT T.ID, T.Date1, T.mDate
FROM (SELECT tb1.ID, tb1.Date1, dbo.Func(tb1.Date1,@pDate2) AS mDate FROM tb1) AS T
WHERE 30 <= T.mDate

However I don't know if it really helps performance, because I did no testing on that case and maybe the sql server does some optimization. If I would need to use the function i wouldn't care even use the next construct

SELECT tb1.ID, tb1.Date1, dbo.Func(tb1.Date1, GETDATE()) 
FROM tb1 
WHERE 30 <= dbo.Func(tb1.Date1, GETDATE())

Would be nice if you can make some performance test on this.

于 2014-09-17T08:08:33.860 回答
0

你的问题不清楚,但我还是会回答。

为了在 SQL 查询中使用函数,它必须接受 SQL 数据类型的所有参数,并且必须返回 SQL 数据类型的数据。任何专为仅在 Transact-SQL 过程和函数中使用而设计的类型都不能传递给函数或从函数返回。不过,该函数可以在内部使用这些 T-SQL 数据类型。

如果您的函数满足此条件,那么您使用的语法是正确的。

于 2013-03-07T08:23:51.017 回答