2015-12-16 147 views
1

我有2個表,每個包含4-500k記錄等待操作超時

CREATE TABLE [dbo].[User][UserId] [int] IDENTITY(1,1) NOT NULL, 
[Password] [nvarchar](max) NULL, 
[RoleId] [int] NOT NULL, 
[Name] [nvarchar](max) NULL, 
[Address] [nvarchar](max) NULL, 
[Email] [nvarchar](max) NULL, 
[Landline] [nvarchar](max) NULL, 
[MobileNumberCode] [int] NULL, 
[MobileNumber] [nvarchar](max) NULL, 
[DateOfBirth] [datetime] NULL, 
[MarriageDate] [datetime] NULL, 
[CreatedDate] [datetime] NOT NULL, 
[UpdatedDate] [datetime] NOT NULL, 
[Status] [nvarchar](max) NOT NULL, 
[BranchId] [int] NULL, 
[UserTitle] [nvarchar](50) NULL, 
[MiddleName] [nvarchar](50) NULL, 
[LastName] [nvarchar](50) NULL, 
[HouseNumber] [nvarchar](50) NULL, 
[BuildingNumber] [nvarchar](50) NULL, 
[RoadNumber] [nvarchar](50) NULL, 
[BlockNumber] [nvarchar](50) NULL, 
[City] [nvarchar](50) NULL, 
[NearBranchId] [int] NULL, 
[MobileIsValid] [bit] NULL, 
[EmailIsValid] [bit] NULL, 
[Gender] [nvarchar](50) NULL, 
[SourceId] [int] NULL) 

CREATE TABLE [dbo].[PurchaseOrder] 
[PurchaseOrderId] [int] NOT NULL, 
[BranchId] [int] NOT NULL, 
[PurchaseDate] [datetime] NOT NULL, 
[Amount] [decimal](18, 3) NOT NULL, 
[UserId] [int] NOT NULL, 
[Status] [nvarchar](max) NULL, 
[sbs_no] [int] NOT NULL) 

而且我存儲過程得到利用加入這些表中的數據。

CREATE PROC Sp_SearchCustomer (@FromDate datetime = null, 
@ToDate datetime = null, 
@RegFromDate datetime = null, 
@RegToDate datetime = null) 
AS 
BEGIN 
    select a.UserId,a.Name,b.PurchaseOrderId,b.Amount from dbo.[User] a left  join PurchaseOrder b on a.UserId=b.UserId 
where 
((a.CreatedDate >= ''' + cast(@RegFromDate as varchar) + ''') 
AND (a.CreatedDate <= ''' + cast(@RegToDate as varchar) + ''')) 
and ((b.PurchaseDate >= ''' + cast(@FromDate as varchar) + ''') 
AND (b.PurchaseDate <= ''' + cast(@ToDate as varchar) + ''')) 
END 

以日期執行此過程時,其得到「等待操作超時」異常。請幫助解決這個問題。

回答

2

您的表中和您的過程中的日期都保存爲varchar。這是完美的,沒有必要將它們轉換爲varchar。

除此之外,varchar被引號包圍,不會被執行。這是剛剛開始的字符串:

where ((a.CreatedDate >= 'cast(@RegFromDate as varchar)')... 

也有太多的無用的括號,因爲你正在使用AND

試試這個:

CREATE PROC Sp_SearchCustomer (
    @FromDate datetime = null, 
    @ToDate datetime = null, 
    @RegFromDate datetime = null, 
    @RegToDate datetime = null 
) 
AS 
BEGIN 
    SELECT a.UserId 
     ,a.Name 
     ,b.PurchaseOrderId 
     ,b.Amount 
    FROM dbo.[User] a 
    LEFT JOIN PurchaseOrder b 
     ON a.UserId = b.UserId 
    WHERE 
     a.CreatedDate >= @RegFromDate 
     AND a.CreatedDate <= @RegToDate 
     AND b.PurchaseDate >= @FromDate 
     AND b.PurchaseDate <= @ToDate 
END 

一旦查詢進行了改進,可以再次對其進行測試。 您還應該查看統計信息和索引,並確保統計信息是最新的,並且索引不分片。

進行統計,可以使用:exec sp_updatestats 有關這兩個表上的索引,看看碎片%,並選擇REBUILDREORGANIZE他們。