SQL query execution Issue

Hi,
Facing Database performance issue while runing overnight batches.
Generate tfprof output for that batch and found some sql query which is having high elapsed time. Could any one please let me know what is the issue for this. It will also be great help if anyone suggest what need to be done as per tuning of this sql queries so as to get better responce time.
Waiting for your reply.
Effected SQL List:
INSERT INTO INVTRNEE (TRANS_SESSION, TRANS_SEQUENCE, TRANS_ORG_CHILD,
TRANS_PRD_CHILD, TRANS_TRN_CODE, TRANS_TYPE_CODE, TRANS_DATE, INV_MRPT_CODE,
INV_DRPT_CODE, TRANS_CURR_CODE, PROC_SOURCE, TRANS_REF, TRANS_REF2,
TRANS_QTY, TRANS_RETL, TRANS_COST, TRANS_VAT, TRANS_POS_EXT_TOTAL,
INNER_PK_TECH_KEY, TRANS_INNERS, TRANS_EACHES, TRANS_UOM, TRANS_WEIGHT,
TRANS_WEIGHT_UOM )
VALUES
(:B22 , :B1 , :B2 , :B3 , :B4 , :B5 , :B21 , :B6 , :B7 , :B8 , :B20 , :B19 ,
NULL, :B9 , :B10 , :B11 , 0.0, :B12 , :B13 , :B14 , :B15 , :B16 , :B17 ,
:B18 )
call count cpu elapsed disk query current rows
Parse 722 0.09 0.04 0 0 0 0
Execute 1060 7.96 83.01 11442 21598 88401 149973
Fetch 0 0.00 0.00 0 0 0 0
total 1782 8.05 83.06 11442 21598 88401 149973
Misses in library cache during parse: 1
Optimizer goal: CHOOSE
UPDATE /*+ ROWID(TRFDTLEE) */TRFDTLEE SET TRF_STATUS = :B2
WHERE
ROWID = :B1
call count cpu elapsed disk query current rows
Parse 635 0.03 0.01 0 0 0 0
Execute 49902 14.48 271.25 41803 80704 355837 49902
Fetch 0 0.00 0.00 0 0 0 0
total 50537 14.51 271.27 41803 80704 355837 49902
Misses in library cache during parse: 1
Optimizer goal: CHOOSE
DECLARE
var_trans_session     invtrnee.trans_session%TYPE;
BEGIN
-- ADDED BY SHANKAR ON 08/29/97
-- GET THE NEXT AVAILABLE TRANS_SESSION
bastkey('trans_session',0,var_trans_session,'T');
-- MAS001
uk_trfbapuo_auto(var_trans_session,'UPLOAD','T',300);
-- MAS001 end
END;
call count cpu elapsed disk query current rows
Parse 0 0.00 0.00 0 0 0 0
Execute 1 24191.23 24028.57 8172196 10533885 187888 1
Fetch 0 0.00 0.00 0 0 0 0
total 1 24191.23 24028.57 8172196 10533885 187888 1
Misses in library cache during parse: 0
Misses in library cache during execute: 1
Optimizer goal: CHOOSE
SELECT INNER_PK_TECH_KEY
FROM
PRDPCDEE WHERE PRD_LVL_CHILD = :B1 AND LOOSE_PACK_FLAG = 'T'
call count cpu elapsed disk query current rows
Parse 1 0.01 0.00 0 0 0 0
Execute 56081 1.90 2.03 0 0 0 0
Fetch 56081 11.07 458.58 53792 246017 0 56081
total 112163 12.98 460.61 53792 246017 0 56081
Misses in library cache during parse: 1
Optimizer goal: CHOOSE
******************

First off, be aware of the assumptions I'm making. The SQL you presented above strongly suggests (to me at least) that you have cursor for loops. If that's the case, you need to review what their purpose is and look to convert them into single statement DML commands. For example if you have something like this
DECLARE
    ln_Count        NUMBER;
    ln_SomeValue    NUMBER;
BEGIN
    FOR lcr_Row IN (    SELECT pk_id,col1,col2 FROM some_table)
    LOOP
        SELECT
            COUNT(*)
        INTO
            ln_COunt
        FROM
            target_table
        WHERE
            pk_id = lcr_Row.pk_id;
        IF ln_Count = 0 THEN
            SELECT
                some_value
            INTO
                ln_SomeValue
            FROM
                some_other_table
            WHERE
                pk_id = lcr_Row.col1
            INSERT
            INTO
                target_table
                (   pk_id,
                    some_other_value,
                    col2
            VALUES
                (   lcr_Row.col1,
                    ln_SomeValue,
                    lcr_Row.col2
        ELSE
            UPDATE
                target_table
            SET
                some_other_value = ln_SomeValue
            WHERE
                pk_id = lcr_Row.col1;
        END IF;
    END LOOP;
END;                            it could be rewritten as
DECLARE
BEGIN
    MERGE INTO target_table b
    USING ( SELECT
                a.pk_id,
                a.col2,
                b.some_value
            FROM
                some_table a,
                some_other_table b
            WHERE
                b.pk_id = a.col1
           ) e
    ON (b.pk_id = e.pk_id)
    WHEN MATCHED THEN
      UPDATE SET b.some_other_value = e.some_value
    WHEN NOT MATCHED THEN
      INSERT (  b.pk_id,
                b.col2,
                b.some_other_value)
      VALUES(   b.pk_id,
                b.col2,
                b.some_value);
END;It's going to take a bit of analysis and work but the fastest and most scalable way to approach processing data is to use SQL rather than PL/SQL. PL/SQL data processing i.e. cursor loops should be an option of last resort.
HTH
David

Similar Messages

  • SQL query performance issues.

    Hi All,
    I worked on the query a month ago and the fix worked for me in test intance but failed in production. Following is the URL for the previous thread.
    SQL query performance issues.
    Following is the tkprof file.
    CURSOR_ID:76  LENGTH:2383  ADDRESS:f6b40ab0  HASH_VALUE:2459471753  OPTIMIZER_GOAL:ALL_ROWS  USER_ID:443 (APPS)
    insert into cos_temp(
    TRX_DATE, DEPT, PRODUCT_LINE, PART_NUMBER,
    CUSTOMER_NUMBER, QUANTITY_SOLD, ORDER_NUMBER,
    INVOICE_NUMBER, EXT_SALES, EXT_COS,
    GROSS_PROFIT, ACCT_DATE,
    SHIPMENT_TYPE,
    FROM_ORGANIZATION_ID,
    FROM_ORGANIZATION_CODE)
    select a.trx_date,
    g.segment5 dept,
    g.segment4 prd,
    m.segment1 part,
    d.customer_number customer,
    b.quantity_invoiced units,
    --       substr(a.sales_order,1,6) order#,
    substr(ltrim(b.interface_line_attribute1),1,10) order#,
    a.trx_number invoice,
    (b.quantity_invoiced * b.unit_selling_price) sales,
    (b.quantity_invoiced * nvl(price.operand,0)) cos,
    (b.quantity_invoiced * b.unit_selling_price) -
    (b.quantity_invoiced * nvl(price.operand,0)) profit,
    to_char(to_date('2010/02/28 00:00:00','yyyy/mm/dd HH24:MI:SS'),'DD-MON-RR') acct_date,
    'DRP',
    l.ship_from_org_id,
    p.organization_code
    from   ra_customers d,
    gl_code_combinations g,
    mtl_system_items m,
    ra_cust_trx_line_gl_dist c,
    ra_customer_trx_lines b,
    ra_customer_trx_all a,
    apps.oe_order_lines l,
    apps.HR_ORGANIZATION_INFORMATION i,
    apps.MTL_INTERCOMPANY_PARAMETERS inter,
    apps.HZ_CUST_SITE_USES_ALL site,
    apps.qp_list_lines_v price,
    apps.mtl_parameters p
    where a.trx_date between to_date('2010/02/01 00:00:00','yyyy/mm/dd HH24:MI:SS')
    and to_date('2010/02/28 00:00:00','yyyy/mm/dd HH24:MI:SS')+0.9999
    and   a.batch_source_id = 1001     -- Sales order shipped other OU
    and   a.complete_flag = 'Y'
    and   a.customer_trx_id = b.customer_trx_id
    and   b.customer_trx_line_id = c.customer_trx_line_id
    and   a.sold_to_customer_id = d.customer_id
    and   b.inventory_item_id = m.inventory_item_id
    and   m.organization_id
         = decode(substr(g.segment4,1,2),'01',5004,'03',5004,
         '02',5003,'00',5001,5002)
    and   nvl(m.item_type,'0') <> '111'
    and   c.code_combination_id = g.code_combination_id+0
    and   l.line_id = b.interface_line_attribute6
    and   i.organization_id = l.ship_from_org_id
    and   p.organization_id = l.ship_from_org_id
    and   i.org_information3 <> '5108'
    and   inter.ship_organization_id = i.org_information3
    and   inter.sell_organization_id = '5108'
    and   inter.customer_site_id = site.site_use_id
    and   site.price_list_id = price.list_header_id
    and   product_attr_value = to_char(m.inventory_item_id)
    call        count       cpu   elapsed         disk        query      current         rows    misses
    Parse           1      0.47      0.56           11          197            0            0         1
    Execute         1   3733.40   3739.40        34893    519962154           11          188         0
    total           2   3733.87   3739.97        34904    519962351           11          188         1
    |         Rows Row Source Operation
    | ------------ ---------------------------------------------------
    |          188 HASH JOIN (cr=519962149 pr=34889 pw=0 time=2607.35)
    |          741 .TABLE ACCESS BY INDEX ROWID QP_PRICING_ATTRIBUTES (cr=519939426 pr=34889 pw=0 time=2457.32)
    |    254644500 ..NESTED LOOPS (cr=519939265 pr=34777 pw=0 time=3819.67)
    |    254643758 ...NESTED LOOPS (cr=8921833 pr=29939 pw=0 time=1274.41)
    |          741 ....NESTED LOOPS (cr=50042 pr=7230 pw=0 time=11.37)
    |          741 .....NESTED LOOPS (cr=48558 pr=7229 pw=0 time=11.35)
    |          741 ......NESTED LOOPS (cr=47815 pr=7223 pw=0 time=11.32)
    |         3237 .......NESTED LOOPS (cr=41339 pr=7223 pw=0 time=12.42)
    |         3237 ........NESTED LOOPS (cr=38100 pr=7223 pw=0 time=12.39)
    |         3237 .........NESTED LOOPS (cr=28296 pr=7139 pw=0 time=12.29)
    |         1027 ..........NESTED LOOPS (cr=17656 pr=4471 pw=0 time=3.81)
    |         1027 ...........NESTED LOOPS (cr=13537 pr=4404 pw=0 time=3.30)
    |          486 ............NESTED LOOPS (cr=10873 pr=4240 pw=0 time=0.04)
    |          486 .............NESTED LOOPS (cr=10385 pr=4240 pw=0 time=0.03)
    |          486 ..............TABLE ACCESS BY INDEX ROWID RA_CUSTOMER_TRX_ALL (cr=9411 pr=4240 pw=0 time=0.02)
    |        75253 ...............INDEX RANGE SCAN RA_CUSTOMER_TRX_N5 (cr=403 pr=285 pw=0 time=0.38)
    |          486 ..............TABLE ACCESS BY INDEX ROWID HZ_CUST_ACCOUNTS (cr=974 pr=0 pw=0 time=0.01)
    |          486 ...............INDEX UNIQUE SCAN HZ_CUST_ACCOUNTS_U1 (cr=488 pr=0 pw=0 time=0.01)
    |          486 .............INDEX UNIQUE SCAN HZ_PARTIES_U1 (cr=488 pr=0 pw=0 time=0.01)
    |         1027 ............TABLE ACCESS BY INDEX ROWID RA_CUSTOMER_TRX_LINES_ALL (cr=2664 pr=164 pw=0 time=1.95)
    |         2063 .............INDEX RANGE SCAN RA_CUSTOMER_TRX_LINES_N2 (cr=1474 pr=28 pw=0 time=0.22)
    |         1027 ...........TABLE ACCESS BY INDEX ROWID RA_CUST_TRX_LINE_GL_DIST_ALL (cr=4119 pr=67 pw=0 time=0.54)
    |         1027 ............INDEX RANGE SCAN RA_CUST_TRX_LINE_GL_DIST_N1 (cr=3092 pr=31 pw=0 time=0.20)
    |         3237 ..........TABLE ACCESS BY INDEX ROWID MTL_SYSTEM_ITEMS_B (cr=10640 pr=2668 pw=0 time=15.35)
    |         3237 ...........INDEX RANGE SCAN MTL_SYSTEM_ITEMS_B_U1 (cr=2062 pr=40 pw=0 time=0.33)
    |         3237 .........TABLE ACCESS BY INDEX ROWID OE_ORDER_LINES_ALL (cr=9804 pr=84 pw=0 time=0.77)
    |         3237 ..........INDEX UNIQUE SCAN OE_ORDER_LINES_U1 (cr=6476 pr=47 pw=0 time=0.43)
    |         3237 ........TABLE ACCESS BY INDEX ROWID MTL_PARAMETERS (cr=3239 pr=0 pw=0 time=0.04)
    |         3237 .........INDEX UNIQUE SCAN MTL_PARAMETERS_U1 (cr=2 pr=0 pw=0 time=0.01)
    |          741 .......TABLE ACCESS BY INDEX ROWID HR_ORGANIZATION_INFORMATION (cr=6476 pr=0 pw=0 time=0.10)
    |         6474 ........INDEX RANGE SCAN HR_ORGANIZATION_INFORMATIO_FK2 (cr=3239 pr=0 pw=0 time=0.03)Please help.
    Regards
    Ashish

    |    254644500 ..NESTED LOOPS (cr=519939265 pr=34777 pw=0 time=3819.67)
    |    254643758 ...NESTED LOOPS (cr=8921833 pr=29939 pw=0 time=1274.41)There is no way the optimizer should choose to process that many rows using nested loops.
    Either the statistics are not up to date, the data values are skewed or you have some optimizer parameter set to none default to force index access.
    Please post explain plan and optimizer* parameter settings.

  • Excel ADODB Sql Query Execution taking hours when manipulate excel tables

    Hello All 
    I have 28000 records with 8 column in an sheet. When I convert the sheet into ADODB database and copy to new
    excel using below code it is executing in less than a min
    Set Tables_conn_obj = New ADODB.Connection
    Tables_conn_str = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Table_Filename & ";Extended Properties=""Excel 12.0;ReadOnly=False;HDR = Yes;IMEX=1"""
    Tables_conn_obj.Open Tables_conn_str
    First_Temp_sqlqry = "Select * INTO [Excel 12.0;DATABASE=C:\Prod Validation\Database\Second Acat Table.xlsb].[Sheet1] Table [first - Table$];" Tables_conn_obj.Execute First_Temp_sqlqry
    But when I change the query to manipulate one column in current table based on another table in the same excel
    and try to copy the results in another excel, it is taking more than one hour.. why it is taking this much time when both the query results returns the same number of rows and column. I almost spend one week and still not able to resolve this issue.
    Even I tried copyfromrecordset, getrows(), getstring(), Looping each recordset fields options all of them taking
    same amount of time. Why there is huge difference in execution time.
    Important note: Without into statement even below query is executing in few seconds.
    select ( ''''''manipulating first column based on other table data''''''''''''''
    iif(
    [Second - Table$].[Policy Agent] = (select max([ACAT$].[new_Agent_number]) from [ACAT$] where [ACAT$].[new_Agent_number] = [Second - Table$].[Policy Agent] and [ACAT$].[ACAT_EffectiveDate] = ( select MAX([ACAT$].[ACAT_EffectiveDate] ) from [ACAT$] where [ACAT$].[new_Agent_number] = [Second - Table$].[Policy Agent]and [ACAT$].[ACAT_EffectiveDate] > '2014-10-01') ) , (select max([ACAT$].[Old_Agent_number]) from [ACAT$] where [ACAT$].[new_Agent_number] = [Second - Table$].[Policy Agent] and [ACAT$].[ACAT_EffectiveDate] = ( select MAX([ACAT$].[ACAT_EffectiveDate] ) from [ACAT$] where [ACAT$].[new_Agent_number] = [Second - Table$].[Policy Agent]and [ACAT$].[ACAT_EffectiveDate] > '2014-10-01')) ,
    iif( [Second - Table$].[Policy Agent] = (select max([ACAT$].[Old_Agent_number]) from [ACAT$] where [ACAT$].[Old_Agent_number] = [Second - Table$].[Policy Agent] and [ACAT$].[ACAT_EffectiveDate] = ( select MAX([ACAT$].[ACAT_EffectiveDate] ) from [ACAT$]where [ACA T$].[Old_Agent_number] = [Second - Table$].[Policy Agent]and [ACAT$].[ACAT_EffectiveDate] <= '2014-10-01') ), (select max([ACAT$].[new_Agent_number]) from [ACAT$] where [ACAT$].[Old_Agent_number] = [Second - Table$].[Policy Agent] and [ACAT$].[ACAT_EffectiveDate] = ( select MAX([ACAT$].[ACAT_EffectiveDate] ) from [ACAT$] where [ACAT$].[Old_Agent_number] = [Second - Table$].[Policy Agent]and [ACAT$].[ACAT_EffectiveDate] <= '2014-10-01')) ,
    [Second - Table$].[Policy Agent] ))) as [Policy Agent],
    ''''''summing up all other columns''''''''''''''
    (iif(isnull(sum([Second - Table$].[Auto BW-Line Of Business Detail])),0,sum([Second - Table$].[Auto BW-Line Of Business Detail]))) as [Auto BW-Line Of Business Detail],(iif(isnull(sum([Second - Table$].[Auto Farmers])),0,sum([Second - Table$].[Auto Farmers]))) as [Auto Farmers],(iif(isnull(sum([Second - Table$].[MCA])),0,sum([Second - Table$].[MCA]))) as [MCA],(iif(isnull(sum([Second - Table$].[CEA])),0,sum([Second - Table$].[CEA]))) as [CEA],(iif(isnull(sum([Second - Table$].[Commercial P&C])),0,sum([Second - Table$].[Commercial P&C]))) as [Commercial P&C],(iif(isnull(sum([Second - Table$].[Comm WC])),0,sum([Second - Table$].[Comm WC]))) as [Comm WC],(iif(isnull(sum([Second - Table$].[Fire Farmers])),0,sum([Second - Table$].[Fire Farmers]))) as [Fire Farmers],(iif(isnull(sum([Second - Table$].[Flood])),0,sum([Second - Table$].[Flood]))) as [Flood],(iif(isnull(sum([Second - Table$].[Kraft Lake])),0,sum([Second - Table$].[Kraft Lake]))) as [Kraft Lake],(iif(isnull(sum([Second - Table$].[Life])),0,sum([Second - Table$].[Life]))) as [Life],(iif(isnull(sum([Second - Table$].[Foremost])),0,sum([Second - Table$].[Foremost]))) as [Foremost],(iif(isnull(sum([Second - Table$].[Umbrella])),0,sum([Second - Table$].[Umbrella]))) as [Umbrella],(iif(isnull(sum([Second - Table$].[MCNA])),0,sum([Second - Table$].[MCNA]))) as [MCNA]
    INTO [Excel 12.0;DATABASE=C:\Prod Validation\Database\Second Acat Table.xlsb].[Sheet1]
    from [Second - Table$] group by [Second - Table$].[Policy Agent] ;

    Hi Fei,
      Thank you so much for the reply post. I just executed the same above SQL without INTO Statement and assigned the SQL result to ADODB recordset as below. If the time difference is due to the SQL query then below statements also should execute for hours
    right, but it gets executed in seconds. But to copy the recordset to excel again it is taking hours. I tried copyfromrecordset,
    getrows(), getstring(), Looping each recordset fields options and all of them taking same amount of time. Please let me know there is delay in time for this much small data
    Even I tried to typecast all columns to double, string in SQL and still the execution time  is not reduced. 
    First_Temp_Recordset.Open sql_qry, Tables_conn_obj, adOpenStatic, adLockOptimistic ''' OR SET First_Temp_Recordset = Tables_conn_obj.Execute sql_qry

  • Excel ADODB Sql Query Execution taking hours when manipulate excel tables why?

    I have 28000 records with 8 column in an sheet. When I convert the sheet into ADODB database and copy to new excel using below code it is executing in less than a min
    Set Tables_conn_obj = New ADODB.Connection Tables_conn_str = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Table_Filename & ";Extended Properties=""Excel 12.0;ReadOnly=False;HDR = Yes;IMEX=1""" Tables_conn_obj.Open
    Tables_conn_str First_Temp_sqlqry = "Select * INTO [Excel 12.0;DATABASE=C:\Prod Validation\Database\Second Acat Table.xlsb].[Sheet1] Table [first - Table$];" Tables_conn_obj.Execute First_Temp_sqlqry
    But when I change the query to manipulate one column in current table based on another table in the same excel and try to copy the results in another excel, it is taking more than one hour.. why it is taking this much time when both the query results returns
    the same number of rows and column. I almost spend one week and still not able to resolve this issue.
    Even I tried copyfromrecordset, getrows(), getstring(), Looping each recordset fields options all of them taking same amount of time. Appreciate any inputs...
    select ( ''''''manipulating first column based on other table data''''''''''''''
    iif( [Second - Table$].[Policy Agent] = (select max([ACAT$].[new_Agent_number]) from [ACAT$] where [ACAT$].[new_Agent_number] = [Second - Table$].[Policy Agent] and [ACAT$].[ACAT_EffectiveDate] = ( select MAX([ACAT$].[ACAT_EffectiveDate] ) from [ACAT$] where
    [ACAT$].[new_Agent_number] = [Second - Table$].[Policy Agent]and [ACAT$].[ACAT_EffectiveDate] > '2014-10-01') ) , (select max([ACAT$].[Old_Agent_number]) from [ACAT$] where [ACAT$].[new_Agent_number] = [Second - Table$].[Policy Agent] and [ACAT$].[ACAT_EffectiveDate]
    = ( select MAX([ACAT$].[ACAT_EffectiveDate] ) from [ACAT$] where [ACAT$].[new_Agent_number] = [Second - Table$].[Policy Agent]and [ACAT$].[ACAT_EffectiveDate] > '2014-10-01')) ,
    iif( [Second - Table$].[Policy Agent] = (select max([ACAT$].[Old_Agent_number]) from [ACAT$] where [ACAT$].[Old_Agent_number] = [Second - Table$].[Policy Agent] and [ACAT$].[ACAT_EffectiveDate] = ( select MAX([ACAT$].[ACAT_EffectiveDate] ) from [ACAT$]where
    [ACA T$].[Old_Agent_number] = [Second - Table$].[Policy Agent]and [ACAT$].[ACAT_EffectiveDate] <= '2014-10-01') ), (select max([ACAT$].[new_Agent_number]) from [ACAT$] where [ACAT$].[Old_Agent_number] = [Second - Table$].[Policy Agent] and [ACAT$].[ACAT_EffectiveDate]
    = ( select MAX([ACAT$].[ACAT_EffectiveDate] ) from [ACAT$] where [ACAT$].[Old_Agent_number] = [Second - Table$].[Policy Agent]and [ACAT$].[ACAT_EffectiveDate] <= '2014-10-01')) ,
    [Second - Table$].[Policy Agent] ))) as [Policy Agent],
    ''''''summing up all other columns''''''''''''''
    (iif(isnull(sum([Second - Table$].[Auto BW-Line Of Business Detail])),0,sum([Second - Table$].[Auto BW-Line Of Business Detail]))) as [Auto BW-Line Of Business Detail],(iif(isnull(sum([Second - Table$].[Auto Farmers])),0,sum([Second - Table$].[Auto Farmers])))
    as [Auto Farmers],(iif(isnull(sum([Second - Table$].[MCA])),0,sum([Second - Table$].[MCA]))) as [MCA],(iif(isnull(sum([Second - Table$].[CEA])),0,sum([Second - Table$].[CEA]))) as [CEA],(iif(isnull(sum([Second - Table$].[Commercial P&C])),0,sum([Second
    - Table$].[Commercial P&C]))) as [Commercial P&C],(iif(isnull(sum([Second - Table$].[Comm WC])),0,sum([Second - Table$].[Comm WC]))) as [Comm WC],(iif(isnull(sum([Second - Table$].[Fire Farmers])),0,sum([Second - Table$].[Fire Farmers]))) as [Fire
    Farmers],(iif(isnull(sum([Second - Table$].[Flood])),0,sum([Second - Table$].[Flood]))) as [Flood],(iif(isnull(sum([Second - Table$].[Kraft Lake])),0,sum([Second - Table$].[Kraft Lake]))) as [Kraft Lake],(iif(isnull(sum([Second - Table$].[Life])),0,sum([Second
    - Table$].[Life]))) as [Life],(iif(isnull(sum([Second - Table$].[Foremost])),0,sum([Second - Table$].[Foremost]))) as [Foremost],(iif(isnull(sum([Second - Table$].[Umbrella])),0,sum([Second - Table$].[Umbrella]))) as [Umbrella],(iif(isnull(sum([Second - Table$].[MCNA])),0,sum([Second
    - Table$].[MCNA]))) as [MCNA]
    INTO [Excel 12.0;DATABASE=C:\Prod Validation\Database\Second Acat Table.xlsb].[Sheet1]
    from [Second - Table$] group by [Second - Table$].[Policy Agent] ;

    Hi Fei,
      Thank you so much for the reply post. I just executed the same above SQL without INTO Statement and assigned the SQL result to ADODB recordset as below. If the time difference is due to the SQL query then below statements also should execute for hours
    right, but it gets executed in seconds. But to copy the recordset to excel again it is taking hours. I tried copyfromrecordset,
    getrows(), getstring(), Looping each recordset fields options and all of them taking same amount of time. Please let me know there is delay in time for this much small data
    Even I tried to typecast all columns to double, string in SQL and still the execution time  is not reduced. 
    First_Temp_Recordset.Open sql_qry, Tables_conn_obj, adOpenStatic, adLockOptimistic ''' OR SET First_Temp_Recordset = Tables_conn_obj.Execute sql_qry

  • Sql query cache issue

    I am trying to see the log file in Manage sessions for the sql query in Answers. I see that if we run the same report multiple times, the sql query is showing up only the first time. Second time if I run it is not showing up. If I do a brand new report with diff columns picked it is giving me the sql then. Where do I set this option to show the sql query everytime I run a report even if it is the same report run multiple times. Is this caching issue?

    It shouldn't.... Have you unchecked the "Cache" on the physical layer for this table? If you go onto the Advanced tab, is the option "Bypass the Oracle BI cache" checked?

  • SQL query execution in DB02 hangs if record set is more than 50000

    Hi,
    We are facing issue in a report performance. The return is using native SQL query.
    There are custom views created ar database level for pricing/maetrial and stock. The native sql query is written on these views. The report takes around 15 mins to run in background .
    We are trying to analyse the native SQL query through DB02. I tried fetching records for one particular
    custom view to make out if its indexing issue or something else.When i using TOP 35000 records with select query runs fine with this dataset or less than this . If i increase it to 40000 system doesn;t show anything in SQL ouptut. And above one lakh records system gives timeout.
    The count in this view gives some 10 lakh records which I don't feel is v.v.huge that query that too native sql takes so much time.
    Any help on this will be highly appreciated.
    Regards
    Madhu

    what do you expect from that poor information.
    do you change data or onyl select.
    If you use SAP and ABAP, then you should also use Open SQL.
    Otherwise it is possible to run the SQL Trace with Native SQL, it is anyway only Native SQL, what the trace sees.
    Use package size and it will probably work fine.
    Siegfried

  • Exact time of SQL query execution.

    Hi,
    Is there any way to get the exact time of execution of particular SQL query.
    Oracle Version : 10.2.0.4.0
    OS : Sun OS.
    Thx,
    Gowin.

    In general it's pretty hard.
    Look at V$SQLSTAT.ELAPSED_TIME and DBA_HIST_SQLSTAT.ELAPSED_TIME_TOTAL/DELTA (need a license).
    It will give you accurate results for a non-parallel query. For parallel queries you'll get a total time spent by all slaves.
    Also you can enable tracing either on database or session level and analyze the trace files generated.
    Edited by: Max Seleznev on Nov 4, 2011 12:06 PM

  • Sql query execution in jsp

    can u help me to print multiple rows resulted from a sql query using jsp.

    Map the ResultSet to a Collection of DTO's, use the JSTL's c:forEach tag to iterate through it inside a JSP page, use the HTML table, tr and td elements to present the data in a table.

  • SQL Query execution with LISTAGG

    Hello,
    I am trying to get some data using LISTAGG functionality.
    I have below query with works fine with the table, but not with the rowsource which is based on same table.
    SELECT COL1,LISTAGG(COL3, ',') WITHIN GROUP (ORDER BY COL2) AS fieldName FROM IOP_Sample_RS GROUP BY COL1it gives parsing error
    line 1:22: expecting "FROM", found '('col 22 is '(' of LISTAGG function.
    One more Question
    Does UNION, MINUS works with RSQL in IOP?
    Thanks,
    Sumant Chhunchha.
    Edited by: Sumant on Jun 15, 2011 5:04 AM

    LISTAGG, UNION, MINUS is not supported with RSQL, instead you can massage your SQL query to load data into IOP and then use a simple RSQL query.

  • Clustering of SQL query execution times

    In doing some query execution experiments I have noted a curious (to me, anyhow) clustering of execution times around two distinct points. Across about 100 tests each running 1000 queries using (pseudo-)randomly generated IDs the following pattern emerges. The queries were run from Java using all combinations of pooled/non-pooled and thin/oci driver combinations:
         100          *
         90          *
    R     80          *
    u     70          *
    n     60          *
    s     50          *
         40          *                                             *
         30          *                                             *
         20          *                                        *     *     *
         10          *     *                              *     *     *     *     
              0     100     200     300     400     500     600     700     800     900     1000     1100     1200
                                       Time(ms)Where about half of the total execution times cluster strongly about a given (short) time value with a smaller but broader clustering at a significantly slower mark, with zero intermediate values. The last point is the one I find most curious.
    What I would have expected is something like this:
         100          
         90          
    R     80          
    u     70          
    n     60          
    s     50          
         40                              *                         
         30                         *     *     *                    
         20                    *     *     *     *     *     *          
         10          *     *     *     *     *     *     *     *     *     *          
              0     100     200     300     400     500     600     700     800     900     1000     1100     1200
                                       Time(ms)The variables I have tentatively discounted thus far:
    -query differences (single query used)
    -connection differences (using single pooled connection)
    -garbage collection (collection spikes independent of query execution times)
    -amount of data returned in bytes (single varchar2 returned and size is independent of execution time)
    -driver differences (thin and oci compared, overall times differ but pattern of clustering remains)
    -differences between Statement and PreparedStatement usage (both show same pattern)
    I know this is a rather open-ended question, but does the described pattern seem faniliar or spark any thoughts?
    DB-side file I/O?
    Thread time-slicing variations (client or DB-side)?
    FWIW, the DB is 9.2.0.3 DB and the clients are running on WinXP with Java 5.0 and 9i drivers.
    Thanks and regards,
    M

    Further context:
    Are your queries only SELECT queries ?
    Yes, the same SELECT query is used for all tests. The only variable is the bind variable used to identify the primary key of the selection set (i.e. SELECT a.* from a, b, c where a.x = b.x and b.y = c.y and c.pk = ?) where all PKs and FKs are indexed.Do the queries always use the same tables, the same where clauses ?
    Yes, the same tables are always invoked. The where clauses invoked are identical with the excepton of the single bind variable as described above.Do your queries always use bind variables ?
    A single bind variable is used in all invocations as described above.Are your queries also running in single user mode or multi user mode (do you use SELECT FOR UPDATE ?) ?
    We are not using SELECT FOR UPDATEDid something else run on the database/on the server hosting the database on the same time ?
    I have not eliminated the idea, but the test has been repeated roughly 100 times over the course of a week and at different times of day with the same pattern emerging. I suppose it is not out of the question that a resource-hogging process is running consistently and constantly on the DB-side box.Thanks for the input,
    M

  • SQL Query Tuning issue

    A query run by the 'tom' user who searches on (xyz crieteria) takes less than 5 seconds.
    However, when the user 'greg' ruuns the same query, it take > 14 minutes to execute for same xyz crieteria.
    Note:both are application users and internally use DOCD database user.Both are using same SQL Explain plan but diffrence is disk read in case of long running query.
    my question is if both queries are same and using same explain plan and returning same rows why there is disk read???? and such huge diffrence in execution time...Below is the tkprof output for both the queries.
    QUICK QUERY
    ===========
    SELECT E_NAME, E_CURVER_NUM, E_CURVER_CKO, E_PROTECTED, E_INA01, E_INA26,
    E_INA47, V_FILE_NAME, E_ICON_TITLE, E_INA41, E_INA11, E_INA16, E_INA40,
    E_INA15, E_INA35, E_ORG_FILENAME, E_COMMENT, E_INA28, E_INA27,
    E_CREATE_DATE, E_OWNER, E_LAST_DATE, V_CHECKED_OUT, V_CHECKIN_USER, V_NAME,
    V_E_NAME, V_AVAIL_STAT, V_RECLAIM, V_PERMANENT, V_CSI_STATUS, V_CD, E_INA01,
    V_INA03, V_INA02, V_INA04, E_INA02, V_INA01, V_CREATE_DATE, E_INA03
    FROM
    ELEMENT, VERSION WHERE (NLS_UPPER(E_INA01) LIKE NLS_UPPER(:V001) AND
    NLS_UPPER(E_INA26) = NLS_UPPER(:V002) AND E_INA02 IS NULL AND (E_INA03 IS
    NULL OR E_INA03 = :V003) AND V_BRANCH_CURVER = :V004) AND ELEMENT.E_NAME =
    VERSION.V_E_NAME ORDER BY 12, 10 DESC, 1, 26, 25
    call count cpu elapsed disk query current rows
    Parse 1 0.01 0.00 0 0 0 0
    Execute 1 0.00 0.00 0 0 0 0
    Fetch 167 0.18 0.18 0 29466 0 1002
    total 169 0.20 0.19 0 29466 0 1002
    Misses in library cache during parse: 1
    Misses in library cache during execute: 1
    Optimizer goal: CHOOSE
    Parsing user id: 41
    Rows Row Source Operation
    1002 SORT ORDER BY (cr=29466 r=0 w=0 time=179192 us)
    8847 NESTED LOOPS (cr=29466 r=0 w=0 time=146638 us)
    14191 TABLE ACCESS FULL VERSION (cr=1082 r=0 w=0 time=25337 us)
    8847 TABLE ACCESS BY INDEX ROWID ELEMENT (cr=28384 r=0 w=0 time=97209 us)
    14191 INDEX UNIQUE SCAN UI256 (cr=14193 r=0 w=0 time=30388 us)(object id 29956)
    SLOW QUERY
    ==========
    SELECT E_NAME, E_CURVER_NUM, E_CURVER_CKO, E_PROTECTED, E_INA01, E_INA26,
    E_INA47, V_FILE_NAME, E_ICON_TITLE, E_INA41, E_INA11, E_INA16, E_INA40,
    E_INA15, E_INA35, E_ORG_FILENAME, E_COMMENT, E_INA28, E_INA27,
    E_CREATE_DATE, E_OWNER, E_LAST_DATE, V_CHECKED_OUT, V_CHECKIN_USER, V_NAME,
    V_E_NAME, V_AVAIL_STAT, V_RECLAIM, V_PERMANENT, V_CSI_STATUS, V_CD, E_INA01,
    V_INA03, V_INA02, V_INA04, E_INA02, V_INA01, V_CREATE_DATE, E_INA03
    FROM
    ELEMENT, VERSION WHERE (NLS_UPPER(E_INA01) LIKE NLS_UPPER(:V001) AND
    NLS_UPPER(E_INA26) = NLS_UPPER(:V002) AND E_INA02 IS NULL AND (E_INA03 IS
    NULL OR E_INA03 = :V003) AND V_BRANCH_CURVER = :V004) AND ELEMENT.E_NAME =
    VERSION.V_E_NAME ORDER BY 12, 10 DESC, 1, 26, 25
    call count cpu elapsed disk query current rows
    Parse 1 0.01 0.02 2 2 0 0
    Execute 1 0.01 0.00 0 0 0 0
    Fetch 167 0.29 1.18 2389 29466 0 1002
    total 169 0.32 1.21 2391 29468 0 1002
    Misses in library cache during parse: 1
    Misses in library cache during execute: 1
    Optimizer goal: CHOOSE
    Parsing user id: 41
    Rows Row Source Operation
    1002 SORT ORDER BY (cr=29466 r=2389 w=0 time=1180072 us)
    8847 NESTED LOOPS (cr=29466 r=2389 w=0 time=1144811 us)
    14191 TABLE ACCESS FULL VERSION (cr=1082 r=1078 w=0 time=134164 us)
    8847 TABLE ACCESS BY INDEX ROWID ELEMENT (cr=28384 r=1311 w=0 time=984455 us)
    14191 INDEX UNIQUE SCAN UI256 (cr=14193 r=137 w=0 time=127843 us)(object id 29956)

    Anuj,
    In the future, when posting items to the forum where spacing is critical to proper understanding, please use the { code } tags (without spaces) to retain the spacing.
    It appears that there is more to the story than what has been reported. It is good that you used tkprof, as it shows that there is more to the story. Taking a look at the two executions, the tkprof output shows that the first (quick) execution completed in 0.19 seconds, while the second (slow) execution completed in 1.21 seconds, even with th 2,391 blocks read from disk. My first question, if I were in the same situation, would be what would cause the first execution time to jump from 0.19 seconds to 5 seconds, and the second execution to jump from 1.21 seconds to 840 seconds (14 minutes)?
    In both cases, there is a library cache miss on both the parse and the execute calls - there may be some significance to this.
    In both cases, there were 167 fetch calls to return 1,002 rows, meaning that on average 6 rows were returned on each fetch.
    Let's assume that 'tom', whose query executed quickly, was connected to the database over a T1 connection with a 20ms (0.02 second) ping time. For siimplicity in calculation, assume that there were 170 round trips between the server and the client. The network communication between the client and the server would require at least 3.4 seconds, for a total time to send the query and retrieve the results of about 3.6 seconds. This is a little short of 5 seconds which you reported.
    Let's assume that 'greg', whose query executed slowly, was connected to the database over a satellite connection with a 2000ms (2 second) ping time. With the same number of round trips, the network communication would require about 340 seconds, for a total time to send the query and retrieve the results of about 341.21 seconds (5.7 minutes), about 8 minutes short of the target 14 minutes.
    Was this the only query executed by the clients, or were there multiple queries?
    Were the client computers on the same network segment?
    Did you gather a 10046 trace at level 8 or 12 for the sessions? If so, manually review the wait events in the trace files to see if it is possible to determine what was happening during the 14 minutes. Guessing can be fun, but sometimes you come up 8 minutes short by guessing alone.
    Charles Hooper
    IT Manager/Oracle DBA
    K&M Machine-Fabricating, Inc.

  • Explain SQL Query execution plan: Oracle

    Dear Masters,
    Kindly help me to understand execution plan for an SQL statement. I have following SQL execution plan for a query in system. How should I interpret it. I thank You in advace for your guidance.
    SELECT STATEMENT ( Estimated Costs = 1.372.413 , Estimated #Rows = 0 )
           5 NESTED LOOPS
             ( Estim. Costs = 1.372.413 , Estim. #Rows = 3.125 )
             Estim. CPU-Costs = 55.798.978.498 Estim. IO-Costs = 1.366.482
               2 TABLE ACCESS BY INDEX ROWID MSEG
                 ( Estim. Costs = 1.326.343 , Estim. #Rows = 76.717 )
                 Estim. CPU-Costs = 55.429.596.575 Estim. IO-Costs = 1.320.451
                 Filter Predicates
                   1 INDEX RANGE SCAN MSEG~R
                     ( Estim. Costs = 89.322 , Estim. #Rows = 60.069.500 )
                     Search Columns: 1
                     Estim. CPU-Costs = 2.946.739.229 Estim. IO-Costs = 89.009
                     Access Predicates
               4 TABLE ACCESS BY INDEX ROWID MKPF
                 ( Estim. Costs = 1 , Estim. #Rows = 1 )
                 Estim. CPU-Costs = 4.815 Estim. IO-Costs = 1
                 Filter Predicates
                   3 INDEX UNIQUE SCAN MKPF~0
                     Search Columns: 3
                     Estim. CPU-Costs = 3.229 Estim. IO-Costs = 0
                     Access Predicates

    Hi Panjak,
    Yeahh, there's a huge unperformatic SQL statment, what I can see from this acces plan is:
    1 DBO decided to start the query on index R on MSEG, using only part of the index (only one column) with no good uniqueness, accessing disk IO-Costs for this (60mi records), and expecting many interactions (loops) in memory to filter, see CPU-Costs.
    So with the parameters you gave to SQL, they start in a very bad way.
    2 After that program will access the MSEG commanded by what was found on First step, also with a huge loading from DB and filtering (another where criteria on MSEG fields, not found on index R), reducing the result set to 76.717 rows.
    3/4 With this, program goes direct to primary key index on MKPF with direct access (optimized access) and follow to access database table MKPF.
    5 At last will "loop" the result sets from MSEG and MKPF, mixing the tuplas generating the final result set.
    Do you want to share your SQL, the parameters you are sending and code which generate it with us?
    Regards, Fernando Da Ró

  • SQL query / binding issues on my web page

    This may or maynot be the place to ask, but maybe someone can
    tell me what
    to look at...
    I created a page some time back.. and its displays a few
    fields of data
    based on the id passed to it..
    This works fine, but now that we are trying to improve the
    site a little,
    they want some additonal information displayed
    on the page.. so those changes were made about 2 weeks ago...
    now that some
    of the newer records contain the data
    they want displayed, some data is not displaying.. or it will
    display and
    other fields ( that were displaying before ) are now
    missing.. the web page hasnt been touched in 2 weeks.. if we
    execute the
    store procedure within SQL and within our web program
    it always returns the correct data.. but the fields that i
    have binded to
    the page are taking on a life of there own...
    Not sure if anyone has had this problem, but its getting
    annoying.. when i
    execute this within SQL it returns all the values requested.
    If i execute it
    within dreamweaver to show me what results i will get back it
    works there..
    but after i bind the fields to my page and view it only some
    or all my
    fields do not display any data... but if i play around with
    the order of my
    select statement below i can get some fields to display and
    other
    disappear... and i dont ever touch my webpage again...
    Can anyone shed some light on this issue? Or is there a
    better way to
    display my results so that what i get back with my query will
    always
    display....
    here is my stored procedure that im calling
    SET NOCOUNT ON;
    SELECT
    c.cfname,c.clname,c.cid,h.termcode,h.hiredate,h.lastdate,h.cdateh,
    h.cdatet,h.startdate,h.managername,h.termby,
    availsun1,availsun2,availmon1,availmon2,availtue1,availtue2,
    availwed1,availwed2,availthur1,availthur2,availfri1,availfri2,
    availsat1,availsat2,h.comby,ssn_dash = dbo.SSN_dash(cssn),
    Home = dbo.PhoneNumber_complete_format(chphone),
    Mobile = dbo.PhoneNumber_complete_format(cmphone),
    Other = dbo.PhoneNumber_complete_format(cophone),
    Jobtitle =
    case
    when c.st = '90' then
    (select top 1 j.jobtitle from has.dbo.JobCodes j where j.hjob
    = h.jobid and
    j.hlocation = 'DC')
    else
    (select top 1 j.jobtitle from has.dbo.JobCodes j where j.hjob
    = h.jobid and
    j.hlocation <> 'DC')
    end,
    (Select T.term_reason
    From has.dbo.termcodes T, has_arc.dbo.EmpTermHistory H
    where T.term_val = H.termcode and h.cid = @cid) as
    TermReason,
    Days = @day,
    Months = @month,
    Years = @year
    FROM has_arc.dbo.EmpCandidate C, has_arc.dbo.EmpTermHistory H
    WHERE C.cid = @cid AND C.cid = H.cid
    END
    ASP, SQL2005, DW8 VBScript

    And when it says read the columns left to right... i would
    imagine that
    means my select statement should select the columns in the
    order of which
    they are in the tables?
    so in my case.. if HomePhone is last column in my table it
    should be the
    last in the select statement?
    ASP, SQL2005, DW8 VBScript
    "Daniel" <[email protected]> wrote in message
    news:[email protected]...
    > Now when you say TEXT type.. your refering to the data
    types i have setup
    > in the database? correct
    >
    > Within the database the fields that im querying are
    pretty much all
    > varchar a few are date and one int
    >
    >
    >
    >
    > --
    > ASP, SQL2005, DW8 VBScript
    > "Joris van Lier" <[email protected]> wrote in
    message
    > news:[email protected]...
    >>
    >>
    >> "Daniel" <[email protected]> wrote in message
    >> news:[email protected]...
    >>> This may or maynot be the place to ask, but
    maybe someone can tell me
    >>> what
    >>> to look at...
    >>>
    >>> I created a page some time back.. and its
    displays a few fields of data
    >>> based on the id passed to it..
    >>> This works fine, but now that we are trying to
    improve the site a
    >>> little,
    >>> they want some additonal information displayed
    >>> on the page.. so those changes were made about 2
    weeks ago... now that
    >>> some
    >>> of the newer records contain the data
    >>> they want displayed, some data is not
    displaying.. or it will display
    >>> and
    >>> other fields ( that were displaying before ) are
    now
    >>> missing.. the web page hasnt been touched in 2
    weeks.. if we execute the
    >>> store procedure within SQL and within our web
    program
    >>> it always returns the correct data.. but the
    fields that i have binded
    >>> to
    >>> the page are taking on a life of there own...
    >>>
    >>> Not sure if anyone has had this problem, but its
    getting annoying.. when
    >>> i
    >>> execute this within SQL it returns all the
    values requested. If i
    >>> execute it
    >>> within dreamweaver to show me what results i
    will get back it works
    >>> there..
    >>> but after i bind the fields to my page and view
    it only some or all my
    >>> fields do not display any data... but if i play
    around with the order of
    >>> my
    >>> select statement below i can get some fields to
    display and other
    >>> disappear... and i dont ever touch my webpage
    again...
    >>>
    >>> Can anyone shed some light on this issue? Or is
    there a better way to
    >>> display my results so that what i get back with
    my query will always
    >>> display....
    >>>
    >>> here is my stored procedure that im calling
    >>> SET NOCOUNT ON;
    >>> SELECT
    >>>
    c.cfname,c.clname,c.cid,h.termcode,h.hiredate,h.lastdate,h.cdateh,
    >>> h.cdatet,h.startdate,h.managername,h.termby,
    >>>
    availsun1,availsun2,availmon1,availmon2,availtue1,availtue2,
    >>>
    availwed1,availwed2,availthur1,availthur2,availfri1,availfri2,
    >>> availsat1,availsat2,h.comby,ssn_dash =
    dbo.SSN_dash(cssn),
    >>> Home = dbo.PhoneNumber_complete_format(chphone),
    >>> Mobile =
    dbo.PhoneNumber_complete_format(cmphone),
    >>> Other =
    dbo.PhoneNumber_complete_format(cophone),
    >>> Jobtitle =
    >>> case
    >>> when c.st = '90' then
    >>> (select top 1 j.jobtitle from has.dbo.JobCodes j
    where j.hjob = h.jobid
    >>> and
    >>> j.hlocation = 'DC')
    >>> else
    >>> (select top 1 j.jobtitle from has.dbo.JobCodes j
    where j.hjob = h.jobid
    >>> and
    >>> j.hlocation <> 'DC')
    >>> end,
    >>> (Select T.term_reason
    >>> From has.dbo.termcodes T,
    has_arc.dbo.EmpTermHistory H
    >>> where T.term_val = H.termcode and h.cid = @cid)
    as TermReason,
    >>> Days = @day,
    >>> Months = @month,
    >>> Years = @year
    >>>
    >>> FROM has_arc.dbo.EmpCandidate C,
    has_arc.dbo.EmpTermHistory H
    >>> WHERE C.cid = @cid AND C.cid = H.cid
    >>> END
    >>>
    >>>
    >>> --
    >>> ASP, SQL2005, DW8 VBScript
    >>
    >>
    >> Are any of these fields by chance of TEXT type (or
    other Binary Large
    >> OBject type)?
    >> In this case there are certain limitations the text
    fields must be the
    >> last in your SQL statement and may only
    >> be retrieved ONCE reliably.
    >>
    >> <%
    >> Dim myTextVar
    >> myTextVar = Recordset.Fields.Item("TEXTFIELD").value
    >> %>
    >> <% If NOT IsNull(myTextVar) Then%>
    >> <%=(Replace(myTextVar, chr(13),
    "<BR>"))%>
    >> <% End If ' NOT IsNull(myTextVar) %>
    >>
    >> Here's an excerpt from the Microsoft Site
    >>
    >> When dealing with BLOB fields from Microsoft SQL
    Server, you must put
    >> them
    >> to the right of non-BLOB columns in the resultset.
    To be safe, you should
    >> also read the columns in left-to-right order, so if
    you have two BLOB
    >> columns as the last two columns in your resultset,
    read the first one and
    >> then the second. Do not read them in the reverse
    order.
    >> MS:
    http://support.microsoft.com/support/kb/articles/q175/2/39.asp
    >>
    >> Joris van Lier
    >
    >

  • SQL query / binding issues within dreamweaver

    Not sure if anyone has had this problem, but its getting
    annoying.. when i
    execute this within SQL it returns all the values requested.
    If i execute it
    within dreamweaver to show me what results i will get back it
    works there..
    but after i bind the fields to my page and view it only some
    or all my
    fields do not display any data... but if i play around with
    the order of my
    select statement below i can get some fields to display and
    other
    disappear... and i dont ever touch my webpage again...
    Can anyone shed some light on this issue? Or is there a
    better way to
    display my results so that what i get back with my query will
    always
    display....
    here is my stored procedure that im calling
    SET NOCOUNT ON;
    SELECT
    c.cfname,c.clname,c.cid,h.termcode,h.hiredate,h.lastdate,h.cdateh,
    h.cdatet,h.startdate,h.managername,h.termby,
    availsun1,availsun2,availmon1,availmon2,availtue1,availtue2,
    availwed1,availwed2,availthur1,availthur2,availfri1,availfri2,
    availsat1,availsat2,h.comby,ssn_dash = dbo.SSN_dash(cssn),
    Home = dbo.PhoneNumber_complete_format(chphone),
    Mobile = dbo.PhoneNumber_complete_format(cmphone),
    Other = dbo.PhoneNumber_complete_format(cophone),
    Jobtitle =
    case
    when c.st = '90' then
    (select top 1 j.jobtitle from has.dbo.JobCodes j where j.hjob
    = h.jobid and
    j.hlocation = 'DC')
    else
    (select top 1 j.jobtitle from has.dbo.JobCodes j where j.hjob
    = h.jobid and
    j.hlocation <> 'DC')
    end,
    (Select T.term_reason
    From has.dbo.termcodes T, has_arc.dbo.EmpTermHistory H
    where T.term_val = H.termcode and h.cid = @cid) as
    TermReason,
    Days = @day,
    Months = @month,
    Years = @year
    FROM has_arc.dbo.EmpCandidate C, has_arc.dbo.EmpTermHistory H
    WHERE C.cid = @cid AND C.cid = H.cid
    END
    ASP, SQL2005, DW8 VBScript

    Can anyone help shed some light on this?
    ASP, SQL2005, DW8 VBScript
    "Daniel" <[email protected]> wrote in message
    news:ff3ud8$10k$[email protected]..
    > Not sure if anyone has had this problem, but its getting
    annoying.. when i
    > execute this within SQL it returns all the values
    requested. If i execute
    > it within dreamweaver to show me what results i will get
    back it works
    > there.. but after i bind the fields to my page and view
    it only some or
    > all my fields do not display any data... but if i play
    around with the
    > order of my select statement below i can get some fields
    to display and
    > other disappear... and i dont ever touch my webpage
    again...
    >
    > Can anyone shed some light on this issue? Or is there a
    better way to
    > display my results so that what i get back with my query
    will always
    > display....
    >
    > here is my stored procedure that im calling
    > SET NOCOUNT ON;
    > SELECT
    >
    c.cfname,c.clname,c.cid,h.termcode,h.hiredate,h.lastdate,h.cdateh,
    > h.cdatet,h.startdate,h.managername,h.termby,
    >
    availsun1,availsun2,availmon1,availmon2,availtue1,availtue2,
    >
    availwed1,availwed2,availthur1,availthur2,availfri1,availfri2,
    > availsat1,availsat2,h.comby,ssn_dash =
    dbo.SSN_dash(cssn),
    > Home = dbo.PhoneNumber_complete_format(chphone),
    > Mobile = dbo.PhoneNumber_complete_format(cmphone),
    > Other = dbo.PhoneNumber_complete_format(cophone),
    > Jobtitle =
    > case
    > when c.st = '90' then
    > (select top 1 j.jobtitle from has.dbo.JobCodes j where
    j.hjob = h.jobid
    > and j.hlocation = 'DC')
    > else
    > (select top 1 j.jobtitle from has.dbo.JobCodes j where
    j.hjob = h.jobid
    > and j.hlocation <> 'DC')
    > end,
    > (Select T.term_reason
    > From has.dbo.termcodes T, has_arc.dbo.EmpTermHistory H
    > where T.term_val = H.termcode and h.cid = @cid) as
    TermReason,
    > Days = @day,
    > Months = @month,
    > Years = @year
    >
    > FROM has_arc.dbo.EmpCandidate C,
    has_arc.dbo.EmpTermHistory H
    > WHERE C.cid = @cid AND C.cid = H.cid
    > END
    >
    >
    > --
    > ASP, SQL2005, DW8 VBScript
    >

  • SQL Query Performance Issue

    Hey,
    Please forgive me if I'm missing something really obvious but it's been a while since I did any SQL work and I'm obviously a bit rusty.
    When the below query is run the CPU on the SQL server maxes out. The query itself takes over 6 hours to run.
    Is there anything glaringly obvious with the query that might be causing thisCheers
    Paul
    SELECT TOP (100) PERCENT dbo.CUSTPACKINGSLIPTRANS.ITEMID AS [Stock Code],
    dbo.CUSTPACKINGSLIPTRANS.SALESUNIT AS [Unit of Sale],
    dbo.DIMENSIONFINANCIALTAG.DESCRIPTION AS [Product Group],
    dbo.INVENTITEMGROUP.ITEMGROUPID AS [Item Group],
    dbo.INVENTTABLE.SECTION,
    dbo.INVENTTABLE.GROUPS AS [Group],
    dbo.INVENTTABLE.SUBGROUPS AS [Sub Group],
    dbo.CUSTPACKINGSLIPJOUR.ORDERACCOUNT AS [Cust Account],
    dbo.CUSTTABLE.INVOICEACCOUNT AS [Invoice Account],
    dbo.DIRPARTYTABLE.NAME AS [Cust Name],
    dbo.CUSTTABLE.CURRENCY,
    dbo.CUSTTABLE.CIT_CONTROLLER AS [Credit Controller],
    dbo.CUSTTABLE.CREDITMAX AS [Credit Limit],
    dbo.CUSTTABLE.CUSTCLASSIFICATIONID AS Classification,
    dbo.DIRPERSONNAME.FIRSTNAME + ' ' + dbo.DIRPERSONNAME.LASTNAME AS [Sales Person],
    dbo.SALESTABLE.SALESGROUP AS [Outside Rooms],
    CASE WHEN CUSTTABLE.CUSTCLASSIFICATIONID = 'Cash' THEN dbo.SALESTABLE.SALESGROUP ELSE dbo.CUSTTABLE.SALESGROUP END AS [Sales Rep],
    dbo.LOGISTICSPOSTALADDRESS.STATE [Customer Region],
    dbo.LOGISTICSPOSTALADDRESS.COUNTY [Customer County],
    dbo.CUSTTABLE.LINEOFBUSINESSID AS [Line Of Business],
    a.DISPLAYVALUE AS [Site/Location],
    dbo.CUSTPACKINGSLIPTRANS.PACKINGSLIPID AS [Delivery Ref],
    dbo.LOGISTICSPOSTALADDRESS.COUNTRYREGIONID,
    CONVERT(varchar(12), dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE, 111) AS [Delivery Date],
    dbo.LOGISTICSPOSTALADDRESS.ADDRESS AS [Delivery Address],
    dbo.CUSTPACKINGSLIPTRANS.VALUEMST AS [Delivery Value (CON)],
    CONVERT(varchar(12), dbo.SALESTABLE.RECEIPTDATEREQUESTED, 111) AS [Requested Delivery Date],
    dbo.SALESTABLE.SALESID AS [Order Ref],
    CASE dbo.SALESTABLE.SALESSTATUS WHEN '0' THEN 'None' WHEN '1' THEN 'Open Order' WHEN '2' THEN 'Delivered' WHEN '3' THEN 'Invoiced' WHEN '4' THEN 'Canceled' END AS [Sales Status],
    CASE dbo.SALESTABLE.SALESTYPE WHEN '0' THEN 'Journal' WHEN '1' THEN 'Quotation' WHEN '2' THEN 'Subscription' WHEN '3' THEN 'Sales Order' WHEN '4' THEN 'Returned Item' WHEN '5' THEN 'Blanket Order' WHEN '6' THEN 'Item Requirements' WHEN '7' THEN 'Undefined' END AS [Sales Type],
    CASE dbo.SALESTABLE.AG_SALESLOCATION WHEN '0' THEN 'None' WHEN '1' THEN 'OR_DGN' WHEN '2' THEN 'OR_FMT' WHEN '3' THEN 'OR_TME' WHEN '4' THEN 'OR_OMA' WHEN '5' THEN 'DSP_DGN' WHEN '6' THEN 'DSP_FMT' WHEN '7' THEN 'DSP_TME' WHEN '8' THEN 'DSP_OMA' WHEN '9' THEN 'DSP_BEL' WHEN '10' THEN 'DSP_CDF' WHEN '11' THEN 'DSP_BGY' WHEN '12' THEN 'Credit Control' WHEN '13' THEN 'Internal Sales' WHEN '14' THEN 'CP_FMT' WHEN '15' THEN 'GBSales' END AS [Sales Location],
    dbo.SALESTABLE.PURCHORDERFORMNUM AS [Customer Requisition],
    dbo.SALESLINE.LINEDISC AS [Line Disc],
    dbo.SALESLINE.LINEPERCENT AS [Line Percent],
    dbo.SALESLINE.PRICEGROUPID AS [Price Group],
    dbo.INVENTDIM.INVENTLOCATIONID AS Warehouse,
    dbo.DIRPARTYTABLE.NAMEALIAS AS [Search Name],
    dbo.CUSTPACKINGSLIPJOUR.LORRYID AS [Lorry ID],
    dbo.CUSTPACKINGSLIPJOUR.LORRYREGNO AS [Lorry Reg],
    dbo.CUSTPACKINGSLIPJOUR.LORRYDRIVER AS [Lorry Driver],
    CASE dbo.SALESLINE.BLOCKED WHEN '0' THEN 'No' WHEN '1' THEN 'Yes' END AS [Stopped?],
    dbo.CUSTPACKINGSLIPTRANS.QTY AS [Qty Delivered],
    dbo.SALESLINE.SALESPRICE AS [Unit Price],
    dbo.CUSTPACKINGSLIPJOUR.CREATEDBY AS [SDN Creator],
    MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) AS Month,
    YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) AS Year,
    DATEPART(week, dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) AS WeekNo,
    CASE MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) WHEN '1' THEN '10' WHEN '2' THEN '11' WHEN '3' THEN '12' WHEN '4' THEN '1' WHEN '5' THEN '2' WHEN '6' THEN '3' WHEN '7' THEN '4' WHEN '8' THEN '5' WHEN '9' THEN '6' WHEN '10' THEN '7' WHEN '11' THEN '8' WHEN '12' THEN '9' END AS [Fin Period], CASE WHEN MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) <= '3' THEN CONVERT(VARCHAR(10), (YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) - 1)) + '/' + CONVERT(VARCHAR(10), YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE)) WHEN MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) >= '4' THEN CONVERT(VARCHAR(10), YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE)) + '/' + CONVERT(VARCHAR(10), (YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) + 1)) END AS [Fin Year],
    CASE WHEN dbo.custpackingsliptrans.salesunit = '100' THEN dbo.CUSTPACKINGSLIPTRANS.SALESUNIT * dbo.CUSTPACKINGSLIPTRANS.QTY WHEN dbo.custpackingsliptrans.salesunit = '1000' THEN dbo.CUSTPACKINGSLIPTRANS.SALESUNIT * dbo.CUSTPACKINGSLIPTRANS.QTY ELSE dbo.CUSTPACKINGSLIPTRANS.QTY END AS [No of Units],
    CASE dbo.INVENTITEMGROUPITEM.ITEMGROUPID WHEN 'Mortar' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Sand' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Decorative Gravel' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Crushed Aggregates' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Lintels' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) / 1000 WHEN 'TBeams' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) / 1000 WHEN 'Aggregates' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Lime' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY * dbo.UNITOFMEASURECONVERSION.FACTOR) WHEN 'Readymix' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) / 1000 ELSE (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY * dbo.UNITOFMEASURECONVERSION.FACTOR) / 1000 END AS Tonnage,
    dbo.INVENTTABLE.NETWEIGHT AS [Net Weight],
    dbo.INVENTTABLE.PRODCOSTA,
    dbo.INVENTTABLE.PRODCOSTB,
    dbo.INVENTTABLE.PRODCOSTC,
    dbo.INVENTTABLE.PRODCOSTD,
    dbo.INVENTTABLE.PRODCOSTE,
    dbo.INVENTTABLE.PRODCOSTF,
    dbo.INVENTTABLE.PRODCOSTG,
    dbo.INVENTTABLE.PRODCOSTH,
    dbo.INVENTTABLE.QTYPERBALE,
    dbo.INVENTTABLE.M2PERBALE,
    dbo.SALESTABLE.SALESTYPE,
    dbo.SALESTABLE.DLVMODE AS [Delivery Mode],
    CONVERT(varchar(12), dbo.SALESTABLE.SHIPPINGDATECONFIRMED, 111) AS [Shipping Date Confirmed],
    CONVERT(varchar(12), dbo.SALESTABLE.CREATEDDATETIME, 111) AS [Created Date],
    dbo.SALESLINE.CUSTGROUP AS [Cust Group],
    dbo.INVENTTABLE.MADETOORDER AS [Made To Order]
    FROM dbo.CUSTPACKINGSLIPTRANS INNER JOIN
    dbo.CUSTPACKINGSLIPJOUR ON dbo.CUSTPACKINGSLIPTRANS.PACKINGSLIPID = dbo.CUSTPACKINGSLIPJOUR.PACKINGSLIPID INNER JOIN
    dbo.SALESLINE ON dbo.CUSTPACKINGSLIPJOUR.SALESID = dbo.SALESLINE.SALESID AND
    dbo.CUSTPACKINGSLIPTRANS.INVENTTRANSID = dbo.SALESLINE.INVENTTRANSID INNER JOIN
    dbo.INVENTTABLE ON dbo.CUSTPACKINGSLIPTRANS.ITEMID = dbo.INVENTTABLE.ITEMID INNER JOIN
    dbo.INVENTITEMGROUPITEM ON dbo.INVENTTABLE.ITEMID = dbo.INVENTITEMGROUPITEM.ITEMID INNER JOIN
    dbo.INVENTITEMGROUP ON dbo.INVENTITEMGROUPITEM.ITEMGROUPID = dbo.INVENTITEMGROUP.ITEMGROUPID INNER JOIN
    dbo.INVENTDIM ON dbo.SALESLINE.INVENTDIMID = dbo.INVENTDIM.INVENTDIMID INNER JOIN
    dbo.CUSTTABLE ON dbo.CUSTPACKINGSLIPJOUR.ORDERACCOUNT = dbo.CUSTTABLE.ACCOUNTNUM INNER JOIN
    dbo.DIRPARTYTABLE ON dbo.CUSTTABLE.PARTY = dbo.DIRPARTYTABLE.RECID INNER JOIN
    dbo.LOGISTICSPOSTALADDRESS ON dbo.DIRPARTYTABLE.PRIMARYADDRESSLOCATION = dbo.LOGISTICSPOSTALADDRESS.LOCATION INNER JOIN
    dbo.SALESTABLE ON dbo.SALESLINE.SALESID = dbo.SALESTABLE.SALESID INNER JOIN
    dbo.DIRPERSONNAME ON dbo.SALESTABLE.WORKERSALESTAKER = dbo.DIRPERSONNAME.RECID INNER JOIN
    dbo.ECORESPRODUCT ON dbo.CUSTPACKINGSLIPTRANS.ITEMID = dbo.ECORESPRODUCT.SEARCHNAME
    AND dbo.INVENTTABLE.ITEMID = dbo.ECORESPRODUCT.DISPLAYPRODUCTNUMBER LEFT OUTER JOIN
    dbo.UNITOFMEASURECONVERSION ON dbo.ECORESPRODUCT.RECID = dbo.UNITOFMEASURECONVERSION.PRODUCT LEFT OUTER JOIN
    dbo.UNITOFMEASURE ON dbo.UNITOFMEASURECONVERSION.TOUNITOFMEASURE = dbo.UNITOFMEASURE.RECID INNER JOIN
    dbo.DEFAULTDIMENSIONVIEW a ON dbo.CUSTPACKINGSLIPTRANS.DEFAULTDIMENSION = a.DEFAULTDIMENSION AND a.NAME = 'Department' LEFT OUTER JOIN
    dbo.DEFAULTDIMENSIONVIEW b ON dbo.INVENTTABLE.DEFAULTDIMENSION = b.DEFAULTDIMENSION AND b.NAME = 'Center' INNER JOIN
    dbo.DIMENSIONFINANCIALTAG ON b.ENTITYINSTANCE = dbo.DIMENSIONFINANCIALTAG.RECID
    WHERE (dbo.CUSTPACKINGSLIPTRANS.DATAAREAID = 'agl') AND
    (dbo.CUSTPACKINGSLIPJOUR.DATAAREAID = 'agl') AND
    (dbo.SALESLINE.DATAAREAID = 'agl') AND
    (dbo.INVENTTABLE.DATAAREAID = 'vuk') AND
    (dbo.INVENTDIM.DATAAREAID = 'agl') AND
    (dbo.CUSTTABLE.DATAAREAID = 'agl') AND
    (dbo.SALESTABLE.DATAAREAID = 'agl') AND
    (CASE WHEN MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) <= '3' THEN (YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) - 1)
    WHEN MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) >= '4' THEN YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) END = 2014)

    Hey,
    Please forgive me if I'm missing something really obvious but it's been a while since I did any SQL work and I'm obviously a bit rusty.
    When the below query is run the CPU on the SQL server maxes out. The query itself takes over 6 hours to run.
    Is there anything glaringly obvious with the query that might be causing thisCheers
    Paul
    SELECT TOP (100) PERCENT dbo.CUSTPACKINGSLIPTRANS.ITEMID AS [Stock Code],
    dbo.CUSTPACKINGSLIPTRANS.SALESUNIT AS [Unit of Sale],
    dbo.DIMENSIONFINANCIALTAG.DESCRIPTION AS [Product Group],
    dbo.INVENTITEMGROUP.ITEMGROUPID AS [Item Group],
    dbo.INVENTTABLE.SECTION,
    dbo.INVENTTABLE.GROUPS AS [Group],
    dbo.INVENTTABLE.SUBGROUPS AS [Sub Group],
    dbo.CUSTPACKINGSLIPJOUR.ORDERACCOUNT AS [Cust Account],
    dbo.CUSTTABLE.INVOICEACCOUNT AS [Invoice Account],
    dbo.DIRPARTYTABLE.NAME AS [Cust Name],
    dbo.CUSTTABLE.CURRENCY,
    dbo.CUSTTABLE.CIT_CONTROLLER AS [Credit Controller],
    dbo.CUSTTABLE.CREDITMAX AS [Credit Limit],
    dbo.CUSTTABLE.CUSTCLASSIFICATIONID AS Classification,
    dbo.DIRPERSONNAME.FIRSTNAME + ' ' + dbo.DIRPERSONNAME.LASTNAME AS [Sales Person],
    dbo.SALESTABLE.SALESGROUP AS [Outside Rooms],
    CASE WHEN CUSTTABLE.CUSTCLASSIFICATIONID = 'Cash' THEN dbo.SALESTABLE.SALESGROUP ELSE dbo.CUSTTABLE.SALESGROUP END AS [Sales Rep],
    dbo.LOGISTICSPOSTALADDRESS.STATE [Customer Region],
    dbo.LOGISTICSPOSTALADDRESS.COUNTY [Customer County],
    dbo.CUSTTABLE.LINEOFBUSINESSID AS [Line Of Business],
    a.DISPLAYVALUE AS [Site/Location],
    dbo.CUSTPACKINGSLIPTRANS.PACKINGSLIPID AS [Delivery Ref],
    dbo.LOGISTICSPOSTALADDRESS.COUNTRYREGIONID,
    CONVERT(varchar(12), dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE, 111) AS [Delivery Date],
    dbo.LOGISTICSPOSTALADDRESS.ADDRESS AS [Delivery Address],
    dbo.CUSTPACKINGSLIPTRANS.VALUEMST AS [Delivery Value (CON)],
    CONVERT(varchar(12), dbo.SALESTABLE.RECEIPTDATEREQUESTED, 111) AS [Requested Delivery Date],
    dbo.SALESTABLE.SALESID AS [Order Ref],
    CASE dbo.SALESTABLE.SALESSTATUS WHEN '0' THEN 'None' WHEN '1' THEN 'Open Order' WHEN '2' THEN 'Delivered' WHEN '3' THEN 'Invoiced' WHEN '4' THEN 'Canceled' END AS [Sales Status],
    CASE dbo.SALESTABLE.SALESTYPE WHEN '0' THEN 'Journal' WHEN '1' THEN 'Quotation' WHEN '2' THEN 'Subscription' WHEN '3' THEN 'Sales Order' WHEN '4' THEN 'Returned Item' WHEN '5' THEN 'Blanket Order' WHEN '6' THEN 'Item Requirements' WHEN '7' THEN 'Undefined' END AS [Sales Type],
    CASE dbo.SALESTABLE.AG_SALESLOCATION WHEN '0' THEN 'None' WHEN '1' THEN 'OR_DGN' WHEN '2' THEN 'OR_FMT' WHEN '3' THEN 'OR_TME' WHEN '4' THEN 'OR_OMA' WHEN '5' THEN 'DSP_DGN' WHEN '6' THEN 'DSP_FMT' WHEN '7' THEN 'DSP_TME' WHEN '8' THEN 'DSP_OMA' WHEN '9' THEN 'DSP_BEL' WHEN '10' THEN 'DSP_CDF' WHEN '11' THEN 'DSP_BGY' WHEN '12' THEN 'Credit Control' WHEN '13' THEN 'Internal Sales' WHEN '14' THEN 'CP_FMT' WHEN '15' THEN 'GBSales' END AS [Sales Location],
    dbo.SALESTABLE.PURCHORDERFORMNUM AS [Customer Requisition],
    dbo.SALESLINE.LINEDISC AS [Line Disc],
    dbo.SALESLINE.LINEPERCENT AS [Line Percent],
    dbo.SALESLINE.PRICEGROUPID AS [Price Group],
    dbo.INVENTDIM.INVENTLOCATIONID AS Warehouse,
    dbo.DIRPARTYTABLE.NAMEALIAS AS [Search Name],
    dbo.CUSTPACKINGSLIPJOUR.LORRYID AS [Lorry ID],
    dbo.CUSTPACKINGSLIPJOUR.LORRYREGNO AS [Lorry Reg],
    dbo.CUSTPACKINGSLIPJOUR.LORRYDRIVER AS [Lorry Driver],
    CASE dbo.SALESLINE.BLOCKED WHEN '0' THEN 'No' WHEN '1' THEN 'Yes' END AS [Stopped?],
    dbo.CUSTPACKINGSLIPTRANS.QTY AS [Qty Delivered],
    dbo.SALESLINE.SALESPRICE AS [Unit Price],
    dbo.CUSTPACKINGSLIPJOUR.CREATEDBY AS [SDN Creator],
    MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) AS Month,
    YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) AS Year,
    DATEPART(week, dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) AS WeekNo,
    CASE MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) WHEN '1' THEN '10' WHEN '2' THEN '11' WHEN '3' THEN '12' WHEN '4' THEN '1' WHEN '5' THEN '2' WHEN '6' THEN '3' WHEN '7' THEN '4' WHEN '8' THEN '5' WHEN '9' THEN '6' WHEN '10' THEN '7' WHEN '11' THEN '8' WHEN '12' THEN '9' END AS [Fin Period], CASE WHEN MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) <= '3' THEN CONVERT(VARCHAR(10), (YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) - 1)) + '/' + CONVERT(VARCHAR(10), YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE)) WHEN MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) >= '4' THEN CONVERT(VARCHAR(10), YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE)) + '/' + CONVERT(VARCHAR(10), (YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) + 1)) END AS [Fin Year],
    CASE WHEN dbo.custpackingsliptrans.salesunit = '100' THEN dbo.CUSTPACKINGSLIPTRANS.SALESUNIT * dbo.CUSTPACKINGSLIPTRANS.QTY WHEN dbo.custpackingsliptrans.salesunit = '1000' THEN dbo.CUSTPACKINGSLIPTRANS.SALESUNIT * dbo.CUSTPACKINGSLIPTRANS.QTY ELSE dbo.CUSTPACKINGSLIPTRANS.QTY END AS [No of Units],
    CASE dbo.INVENTITEMGROUPITEM.ITEMGROUPID WHEN 'Mortar' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Sand' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Decorative Gravel' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Crushed Aggregates' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Lintels' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) / 1000 WHEN 'TBeams' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) / 1000 WHEN 'Aggregates' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Lime' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY * dbo.UNITOFMEASURECONVERSION.FACTOR) WHEN 'Readymix' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) / 1000 ELSE (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY * dbo.UNITOFMEASURECONVERSION.FACTOR) / 1000 END AS Tonnage,
    dbo.INVENTTABLE.NETWEIGHT AS [Net Weight],
    dbo.INVENTTABLE.PRODCOSTA,
    dbo.INVENTTABLE.PRODCOSTB,
    dbo.INVENTTABLE.PRODCOSTC,
    dbo.INVENTTABLE.PRODCOSTD,
    dbo.INVENTTABLE.PRODCOSTE,
    dbo.INVENTTABLE.PRODCOSTF,
    dbo.INVENTTABLE.PRODCOSTG,
    dbo.INVENTTABLE.PRODCOSTH,
    dbo.INVENTTABLE.QTYPERBALE,
    dbo.INVENTTABLE.M2PERBALE,
    dbo.SALESTABLE.SALESTYPE,
    dbo.SALESTABLE.DLVMODE AS [Delivery Mode],
    CONVERT(varchar(12), dbo.SALESTABLE.SHIPPINGDATECONFIRMED, 111) AS [Shipping Date Confirmed],
    CONVERT(varchar(12), dbo.SALESTABLE.CREATEDDATETIME, 111) AS [Created Date],
    dbo.SALESLINE.CUSTGROUP AS [Cust Group],
    dbo.INVENTTABLE.MADETOORDER AS [Made To Order]
    FROM dbo.CUSTPACKINGSLIPTRANS INNER JOIN
    dbo.CUSTPACKINGSLIPJOUR ON dbo.CUSTPACKINGSLIPTRANS.PACKINGSLIPID = dbo.CUSTPACKINGSLIPJOUR.PACKINGSLIPID INNER JOIN
    dbo.SALESLINE ON dbo.CUSTPACKINGSLIPJOUR.SALESID = dbo.SALESLINE.SALESID AND
    dbo.CUSTPACKINGSLIPTRANS.INVENTTRANSID = dbo.SALESLINE.INVENTTRANSID INNER JOIN
    dbo.INVENTTABLE ON dbo.CUSTPACKINGSLIPTRANS.ITEMID = dbo.INVENTTABLE.ITEMID INNER JOIN
    dbo.INVENTITEMGROUPITEM ON dbo.INVENTTABLE.ITEMID = dbo.INVENTITEMGROUPITEM.ITEMID INNER JOIN
    dbo.INVENTITEMGROUP ON dbo.INVENTITEMGROUPITEM.ITEMGROUPID = dbo.INVENTITEMGROUP.ITEMGROUPID INNER JOIN
    dbo.INVENTDIM ON dbo.SALESLINE.INVENTDIMID = dbo.INVENTDIM.INVENTDIMID INNER JOIN
    dbo.CUSTTABLE ON dbo.CUSTPACKINGSLIPJOUR.ORDERACCOUNT = dbo.CUSTTABLE.ACCOUNTNUM INNER JOIN
    dbo.DIRPARTYTABLE ON dbo.CUSTTABLE.PARTY = dbo.DIRPARTYTABLE.RECID INNER JOIN
    dbo.LOGISTICSPOSTALADDRESS ON dbo.DIRPARTYTABLE.PRIMARYADDRESSLOCATION = dbo.LOGISTICSPOSTALADDRESS.LOCATION INNER JOIN
    dbo.SALESTABLE ON dbo.SALESLINE.SALESID = dbo.SALESTABLE.SALESID INNER JOIN
    dbo.DIRPERSONNAME ON dbo.SALESTABLE.WORKERSALESTAKER = dbo.DIRPERSONNAME.RECID INNER JOIN
    dbo.ECORESPRODUCT ON dbo.CUSTPACKINGSLIPTRANS.ITEMID = dbo.ECORESPRODUCT.SEARCHNAME
    AND dbo.INVENTTABLE.ITEMID = dbo.ECORESPRODUCT.DISPLAYPRODUCTNUMBER LEFT OUTER JOIN
    dbo.UNITOFMEASURECONVERSION ON dbo.ECORESPRODUCT.RECID = dbo.UNITOFMEASURECONVERSION.PRODUCT LEFT OUTER JOIN
    dbo.UNITOFMEASURE ON dbo.UNITOFMEASURECONVERSION.TOUNITOFMEASURE = dbo.UNITOFMEASURE.RECID INNER JOIN
    dbo.DEFAULTDIMENSIONVIEW a ON dbo.CUSTPACKINGSLIPTRANS.DEFAULTDIMENSION = a.DEFAULTDIMENSION AND a.NAME = 'Department' LEFT OUTER JOIN
    dbo.DEFAULTDIMENSIONVIEW b ON dbo.INVENTTABLE.DEFAULTDIMENSION = b.DEFAULTDIMENSION AND b.NAME = 'Center' INNER JOIN
    dbo.DIMENSIONFINANCIALTAG ON b.ENTITYINSTANCE = dbo.DIMENSIONFINANCIALTAG.RECID
    WHERE (dbo.CUSTPACKINGSLIPTRANS.DATAAREAID = 'agl') AND
    (dbo.CUSTPACKINGSLIPJOUR.DATAAREAID = 'agl') AND
    (dbo.SALESLINE.DATAAREAID = 'agl') AND
    (dbo.INVENTTABLE.DATAAREAID = 'vuk') AND
    (dbo.INVENTDIM.DATAAREAID = 'agl') AND
    (dbo.CUSTTABLE.DATAAREAID = 'agl') AND
    (dbo.SALESTABLE.DATAAREAID = 'agl') AND
    (CASE WHEN MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) <= '3' THEN (YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) - 1)
    WHEN MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) >= '4' THEN YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) END = 2014)
    Try to minimize joins using intermediary tables, also you can consider limiting data based on date ranges and codes (DATAAREAID) before joining with other tables.

Maybe you are looking for