SQL Server 查詢時間段內數據


方式一:

ALTER Proc [dbo].[usp_Rpt_AcctTypeAudit]
@FromDate        datetime=null,    -- yyyy-mm-dd  (may change in the future!)
@ToDate            datetime=null,    -- yyyy-mm-dd  (may change in the future!)
@UserID            nvarchar(50) = 'ALL'
as
BEGIN
   set nocount on
   if @ToDate is not null
    begin
        set @ToDate=convert(varchar,@ToDate,112)+' 23:59:59:998'
    end

       select 
       AcctType,AcctDesc,HostAcctType,AcctNumLength,
       case [Action] when 'A' then 'Add' when 'D' then 'Delete' when 'M' then 'Before-Modify' when 'N' then 'After-Modify' else '' end as [Action]
       ,UserID,WsID,CrtTime
       from AcctTypeMasterHist with(nolock)
       where (CrtTime >= @FromDate or @FromDate is null)
         and (CrtTime <= @ToDate or @ToDate is null)
         and (UserID = @UserID or @UserID='ALL' or isnull(@UserID,'')='')
       order by crttime,LogID
END

 

 

方式二:

create  PROCEDURE [dbo].[Sp_CCBA_ProcessLogRpt] 
@FromDate datetime,
@ToDate datetime,
@UserID varchar(27),
@Workstation  varchar(28)
AS

Select * from ProcessLogInf
WHERE DATEDIFF(day, @FromDate, AcDate)>= 0
    ANd DATEDIFF(day, AcDate, @ToDate)>= 0
    AND LogUser = CASE RTRIM(@UserID) WHEN 'ALL' THEN LogUser WHEN '' THEN LogUser ELSE @UserID END
    AND LogWs = CASE RTRIM(@Workstation) WHEN 'ALL' THEN LogWs WHEN '' THEN LogWs ELSE @Workstation END

 效率分析:

作為SqlServer內置函數存在的DateDiff,在執行的過程中需要再解釋,跟使用“>”和“<”邏輯關系拼結在語句相比,在執行效率上很大打折扣。

由此可以看出來內置函數DateDiff果然在執行的時候進行了再分析。
那么在以后的使用過程中如果可以用“>”和“<”號這種邏輯關系所能拼結並能夠正確得到結果的使用,可以適當的拋棄使用DateDiff這種SqlServer內置的函數,會相應的提高編寫的Sql語句執行的效率。

摘自:http://tieba.baidu.com/p/2762861623


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM