爲什麼標量值函數似乎會導致查詢的累積運行速度越慢,連續使用它們的次數越多?爲什麼SQL Server標量值函數變慢?
我有這個表是用從第三方購買的數據構建的。
我已經修剪了一些東西,使這篇文章更短...但只是讓你瞭解如何設置的東西。
CREATE TABLE [dbo].[GIS_Location](
[ID] [int] IDENTITY(1,1) NOT NULL, --PK
[Lat] [int] NOT NULL,
[Lon] [int] NOT NULL,
[Postal_Code] [varchar](7) NOT NULL,
[State] [char](2) NOT NULL,
[City] [varchar](30) NOT NULL,
[Country] [char](3) NOT NULL,
CREATE TABLE [dbo].[Address_Location](
[ID] [int] IDENTITY(1,1) NOT NULL, --PK
[Address_Type_ID] [int] NULL,
[Location] [varchar](100) NOT NULL,
[State] [char](2) NOT NULL,
[City] [varchar](30) NOT NULL,
[Postal_Code] [varchar](10) NOT NULL,
[Postal_Extension] [varchar](10) NULL,
[Country_Code] [varchar](10) NULL,
然後我有兩個函數,查找LAT和LON。
CREATE FUNCTION [dbo].[usf_GIS_GET_LAT]
(
@City VARCHAR(30),
@State CHAR(2)
)
RETURNS INT
WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE @LAT INT
SET @LAT = (SELECT TOP 1 LAT FROM GIS_Location WITH(NOLOCK) WHERE [State] = @State AND [City] = @City)
RETURN @LAT
END
CREATE FUNCTION [dbo].[usf_GIS_GET_LON]
(
@City VARCHAR(30),
@State CHAR(2)
)
RETURNS INT
WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE @LON INT
SET @LON = (SELECT TOP 1 LON FROM GIS_Location WITH(NOLOCK) WHERE [State] = @State AND [City] = @City)
RETURN @LON
END
當我運行以下...
SET STATISTICS TIME ON
SELECT
dbo.usf_GIS_GET_LAT(City,[State]) AS Lat,
dbo.usf_GIS_GET_LON(City,[State]) AS Lon
FROM
Address_Location WITH(NOLOCK)
WHERE
ID IN (SELECT TOP 100 ID FROM Address_Location WITH(NOLOCK) ORDER BY ID DESC)
SET STATISTICS TIME OFF
100〜= 8毫秒,200〜= 32毫秒,400〜876 =毫秒
- 編輯 抱歉,我應該已經更清楚了。我不想調整上面列出的查詢。這只是一個示例,顯示執行時間越慢,記錄越多。在真實世界的應用程序中,這些函數被用作where子句的一部分來在城市和州周圍建立一個半徑來包含該地區的所有記錄。
不要灑NOLOCK提示對於不需要它的樣本,NOLOCK的東西實際上與這個問題無關。 – 2009-04-29 02:04:39
如果你不能擺脫「真正的查詢」中的功能,那麼它總是會很慢。舉一個更好的例子,在WHERE中使用函數,我們可以給你一些想法...... – 2009-04-29 15:53:50