Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6858005
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T02:06:12+00:00 2026-05-27T02:06:12+00:00

I have following piece of sql, whilst it is functioning as expected, it is

  • 0

I have following piece of sql, whilst it is functioning as expected, it is a bit slow to return results (by slow I’m talking about 10 seconds to return 1000 results from a months date range). Is it possible for it to be made more efficient and/or quicker? Just to add these are the following indexes I have on the tables:-

  • RecordID – Primary Key Unique Clustered
  • Department – Non clustered
  • Direction – Non clustered
  • LocalCallGroup – Non clustered
  • ServiceProvider – Non clustered
  • StartTime- Non clustered
  • UserID- Non clustered
  • UserLocalStartTime – Non clustered
  • UserLocalTimeOffset – Non clustered
  • UserNumber – Non clustered

Declaration of variables here, removed for post

    SET @TerminatingSQL = '
    SELECT 
        UserNumber, 
        ImageDirection = ''in'', 
        CallingNumber = CASE WHEN callingnumber IN(''Unavailable'',''Unknown'',''+44anonymous@10.81.253.12'',''0anonymous@10.81.253.12'') THEN ''Anonymous'' ELSE callingnumber END,
        CalledNumber,
        StartTime = dateadd(ms,(-datepart(ms,(startTime))),(startTime)),
        AnswerTime = dateadd(ms,(-datepart(ms,(answerTime))),(answerTime)),
        ReleaseTime =  dateadd(ms,(-datepart(ms,(releaseTime))),(releaseTime)),         
        CallDuration =  dateadd(ms,(-datepart(ms,(releaseTime))),(releaseTime)) - dateadd(ms,(-datepart(ms,(answerTime))),(answerTime)),
        TotalDuration = dateadd(ms,(-datepart(ms,(releaseTime))),(releaseTime)) - dateadd(ms,(-datepart(ms,(startTime))),(startTime)),
        terminationCause,
        recordID
    FROM
        dbo.TABLEA' + @Table +'
    WHERE
        serviceProvider IN ( SELECT serviceProvider FROM ccNumbers WHERE CRMID = ' + CONVERT(VARCHAR(10),@CrmId,103) + ')
        AND startTime between ''' + CONVERT(VARCHAR(10),@Fromdate,112) + ''' AND ''' + CONVERT(VARCHAR(10), @ToDate, 112) + '''
        AND Direction = ''terminating''
        AND (Department = ''' + @Department + ''' OR ''' + @Department + ''' = ''ALL'')
        AND (userid = ''' + @Userid + ''' OR ''' + @Userid + ''' = ''ALL'')'

    SET @OriginatingSQL = '
    SELECT 
        UserNumber, 
        ImageDirection = ''out'', 
        CallingNumber = CASE WHEN callingnumber IN(''Unavailable'',''Unknown'',''+44anonymous@10.81.253.12'',''0anonymous@10.81.253.12'') THEN ''Anonymous'' ELSE callingnumber END,
        CalledNumber,
        StartTime = dateadd(ms,(-datepart(ms,(startTime))),(startTime)),
        AnswerTime = dateadd(ms,(-datepart(ms,(answerTime))),(answerTime)),
        ReleaseTime =  dateadd(ms,(-datepart(ms,(releaseTime))),(releaseTime)),         
        CallDuration =  dateadd(ms,(-datepart(ms,(releaseTime))),(releaseTime)) - dateadd(ms,(-datepart(ms,(answerTime))),(answerTime)),
        TotalDuration = dateadd(ms,(-datepart(ms,(releaseTime))),(releaseTime)) - dateadd(ms,(-datepart(ms,(startTime))),(startTime)),
        terminationCause,
        recordID
    FROM
        dbo.TABLEA' + @Table +'
    WHERE
        serviceProvider IN ( SELECT serviceProvider FROM ccNumbers WHERE CRMID = ' + CONVERT(VARCHAR(10),@CrmId,103) + ')
        AND startTime between ''' + CONVERT(VARCHAR(10),@Fromdate,112) + ''' AND ''' + CONVERT(VARCHAR(10), @ToDate, 112) + '''
        AND Direction = ''originating''
        AND (Department = ''' + @Department + ''' OR ''' + @Department + ''' = ''ALL'')
        AND (userid = ''' + @Userid + ''' OR ''' + @Userid + ''' = ''ALL'')'

    SET @MainSelectSQL = @TerminatingSQL + ' Union '  + @OriginatingSQL

    SET @MainSQL = 'SELECT TOP (' + @PageSize + ') 
        [t1].CalledNumber,
        [t1].CallingNumber,
        [t1].UserNumber, 
        [t1].StartTime,
        [t1].AnswerTime,
        [t1].ReleaseTime,
        [t1].ImageDirection,
        [t1].CallDuration,
        [t1].TotalDuration,
        [t1].TerminationCause
    FROM (
        SELECT ROW_NUMBER() OVER (
            ORDER BY [t0].startTime) as [row_number], 
            [t0].CalledNumber,
            [t0].CallingNumber,
            [t0].UserNumber,
            [t0].StartTime,
            [t0].AnswerTime,
            [t0].ReleaseTime,
            [t0].ImageDirection,
            [t0].CallDuration,
            [t0].TotalDuration,
            [t0].TerminationCause
        FROM
            (' + @MainSelectSQL + ')  AS [t0] 
          )  AS [t1]

    WHERE [t1].[row_number] > ' + @Page + ' * ' + @PageSize +';'

    EXEC (@MainSQL)

-- Work out the total number of rows, but don't bother if we have the number already (i.e. when they keep the same parameters and just click paging.

IF  (@CurrentCount IS NULL)
    BEGIN
        DECLARE @TotalCountSQL nvarchar(4000)
        DECLARE @ParameterList NVARCHAR(4000)   

        SET @ParameterList = '@TotalCount int OUTPUT'
        SET @TotalCountSQL = 'SELECT @TotalCount = COUNT(recordId) FROM (' + @MainSelectSQL + ') as a'

        EXEC SP_EXECUTESQL @TotalCountSQL,@ParameterList,@TotalCount=@TotalCount OUTPUT
    END
ELSE
    BEGIN
        SET @TotalCount = @CurrentCount;
    END
END
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T02:06:12+00:00Added an answer on May 27, 2026 at 2:06 am

    Things to improve

    • UNION ALL will remove an implied DISTINCT. The ImageDirection column ensures that there is no overlap anyway, so UNION adds an extra step in the plan

    • Where you have ROW_NUMBER(), add COUNT(*) OVER () to get the total record count. This removes the need for the 2nd call

    Thoughts:

    • Do you have dynamic table names that requires such ugly concatenation?
      Except for that, I see no need for dynamic SQL

    • Consider using a temp table to stage results to simplify complexity

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following piece of SQL: select l.lease_id , l.tenant_trading_name , p.building_name ,
I have the following piece of sql query: Sql += SELECT ISNULL(SUM(COALESCE (a.currency, 0)),
I have the following piece of SQL code that does the following: Obviously looks
I have the following piece of inline SQL that I run from a C#
I have the following piece of SQL that does not work: declare @id INT;
I have written the following piece of code ( sql clr stored procedure )
I have the following piece of SQL that will check if any duplicate records
I have following piece of code: It compiles without problems under gcc-3.4, gcc-4.3, intel
I have the following piece of code pattern: void M1(string s, string v) {
I have the following piece of code which replaces template markers such as %POST_TITLE%

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.