How to insert the select query result into table?

How to insert the select query result into table?
SELECT  top 20 creation_time  
        ,last_execution_time 
        ,total_physical_reads
        ,total_logical_reads  
        ,total_logical_writes
        , execution_count 
        , total_worker_time
        , total_elapsed_time 
        , total_elapsed_time / execution_count avg_elapsed_time
        ,SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,
         ((CASE statement_end_offset 
          WHEN -1 THEN DATALENGTH(st.text)
          ELSE qs.statement_end_offset END 
            - qs.statement_start_offset)/2) + 1) AS statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
ORDER BY total_elapsed_time / execution_count DESC;
Thanks,
Tirumala

1. SELECT INTO
Below method will create table when data is inserted from one table to another table. Its useful when you need exactly same datatype as source table.
Use AdventureWorks2008R2;
Go
---Insert data using SELECT INTO
SELECT AddressLine1, City
INTO BothellAddresses
FROM Person.Address
where City = 'Bothell';
GO
---VERIFY DATA
Select AddressLine1, City
FROM BothellAddresses
---DROP TABLE
DROP TABLE BothellAddresses
GO
2. INSERT INTO SELECT
Below method will need table to be created prior to inserting data. Its really useful when table is already created and you want insert data from
another table.
Use AdventureWorks2008R2;
Go
---Create Table
CREATE TABLE BothellAddresses (AddressLine1 NVARCHAR(60), City NVARCHAR(30))
---Insert into above table using SELECT
INSERT INTO BothellAddresses(AddressLine1, City)
SELECT AddressLine1, City
FROM Person.Address
where City = 'Bothell';
---VERIFY DATA
Select AddressLine1, City
FROM BothellAddresses
---DROP TABLE
DROP TABLE BothellAddresses
GO
Regards,
Vishal Patel
Blog: http://vspatel.co.uk
Site: http://lehrity.com

Similar Messages

  • How to save the workbook's result into table ?

    Dear all:
    Now  I need to output the workbook's result into ta table ,what can i do now?
    If I save a query's result into a table use rscrm_bapi,if the query have two structures ,the result table looks not well, how can do do?

    Read the help files about APD

  • How to convert the sql query result into xml ? PLease..Please..

    I have a table Submission Record which contain a field with mix with text string and xml data type.
    Table name: Submission Record
    Field name: RCA
    Jason
    Tomato
    <Record>AA</Record>
    Fish
    Brother
    <Record>BB</Record>
    <Record>CC</Record>
    Tom is a girl
    Its mixing with text and xml data.
    I wish to convert all into xml data as per request from management.
    my select statement is like below...but i think it may contain syntax error. Wish to get help from here.
    sqltestagain = "select '<DATA>' || RCA || '</DATA>' from Submission Record".
    Expect below will display
    <DATA>Jason</DATA>
    <DATA>Tomato</DATA>
    <DATA><Record>AA</Record></DATA>
    or any other solution for it ??
    I've tried FOR XML....DBMS_XML......but none of it worked.....

    also look at xmlelement
    SQL> select xmlelement("DATA", rca).getstringval() from
      2  (
      3  select 'Jason' RCA from dual union all
      4  select 'Tomato' from dual union all
      5  select '<Record>AA</Record>' from dual
      6  )
      7  /
    XMLELEMENT("DATA",RCA).GETSTRI
    <DATA>Jason</DATA>
    <DATA>Tomato</DATA>
    <DATA>&lt;Record&gt;AA&lt;/Record&gt;</DATA>
    SQL>

  • How to insert the image or logo into the table as a field in webdynpro abap

    Hi Friends,
    Please tell me how to insert the image or logo into the table as a field in webdynpro abap.........

    Hi Alagappan ,
          In your view layout you take table UI element and then you bind it with some context nodes.
    The attributes of your nodes comes as a field.
    Now in these fields you can set various properties and image is one of them.
    Go to ->
    1. View Layout -> Right Click on ROOTUIELEMENTCONTAINER -> INSERT ELEMENT -> TABLE
    2. Right click on table -> Create Binding.
       Here you have to bind it with the appropriate context node.
    You will get two properties here
    a- Standard Cell Editor :- ( make it image )
    b- Standard properties :- ( If required set image properties ).
    3. If you want put image from out side then import it as a mime object and set the source of your table field ( used as a image )
    also have a look :-
    [Image Properties|http://help.sap.com/saphelp_nw04/helpdata/en/f3/1a61a9dc7f2e4199458e964e76b4ba/content.htm]
    Hope this will solve your problem.
    Reply if any case of any issue.
    Thanks & Regards,
    Monishankar C

  • How to save the  selected rows from Advance table into database

    Hi
    I have requirement like..
    In custom page , Manager Search the Candidates and selects the candidate ROWS from advance table.
    The reqt is how to save the selected multiple rows into the database.

    hi Reetesh,
    In Custom page
    Supoose the Recruiter Search is for Position Finance Mangager , it retrieves 100 rows , out of which Recruiter select 10 rows .
    So in Such scenario how to save this 10 rows against Recruiter
    , i mean , Is i need to create custom table, to save Recruiter , these selected 10 rows.
    I hope u understand my question

  • How to optimize the select query that is executed in a cursor for loop?

    Hi Friends,
    I have executed the code below and clocked the times for every line of the code using DBMS_PROFILER.
    CREATE OR REPLACE PROCEDURE TEST
    AS
       p_file_id              NUMBER                                   := 151;
       v_shipper_ind          ah_item.shipper_ind%TYPE;
       v_sales_reserve_ind    ah_item.special_sales_reserve_ind%TYPE;
       v_location_indicator   ah_item.exe_location_ind%TYPE;
       CURSOR activity_c
       IS
          SELECT *
            FROM ah_activity_internal
           WHERE status_id = 30
             AND file_id = p_file_id;
    BEGIN
       DBMS_PROFILER.start_profiler ('TEST');
       FOR rec IN activity_c
       LOOP
          SELECT DISTINCT shipper_ind, special_sales_reserve_ind, exe_location_ind
                     INTO v_shipper_ind, v_sales_reserve_ind, v_location_indicator
                     FROM ah_item --464000 rows in this table
                    WHERE item_id_edw IN (
                             SELECT item_id_edw
                               FROM ah_item_xref --700000 rows in this table
                              WHERE item_code_cust = rec.item_code_cust
                                AND facility_num IN (
                                       SELECT facility_code
                                         FROM ah_chain_div_facility --17 rows in this table
                                        WHERE chain_id = ah_internal_data_pkg.get_chain_id (p_file_id)
                                          AND div_id = (SELECT div_id
                                                          FROM ah_div --8 rows in this table
                                                         WHERE division = rec.division)));
       END LOOP;
       DBMS_PROFILER.stop_profiler;
    EXCEPTION
       WHEN NO_DATA_FOUND
       THEN
          NULL;
       WHEN TOO_MANY_ROWS
       THEN
          NULL;
    END TEST;The SELECT query inside the cursor FOR LOOP took 773 seconds.
    I have tried using BULK COLLECT instead of cursor for loop but it did not help.
    When I took out the select query separately and executed with a sample value then it gave the results in a flash of second.
    All the tables have primary key indexes.
    Any ideas what can be done to make this code perform better?
    Thanks,
    Raj.

    As suggested I'd try merging the queries into a single SQL. You could also rewrite your IN clauses as JOINs and see if that helps, e.g.
    SELECT DISTINCT ai.shipper_ind, ai.special_sales_reserve_ind, ai.exe_location_ind
               INTO v_shipper_ind, v_sales_reserve_ind, v_location_indicator
               FROM ah_item ai, ah_item_xref aix, ah_chain_div_facility acdf, ah_div ad
              WHERE ai.item_id_edw = aix.item_id_edw
                AND aix.item_code_cust = rec.item_code_cust
                AND aix.facility_num = acdf.facility_code
                AND acdf.chain_id = ah_internal_data_pkg.get_chain_id (p_file_id)
                AND acdf.div_id = ad.div_id
                AND ad.division = rec.division;ALSO: You are calling ah_internal_data_pkg.get_chain_id (p_file_id) every time. Why not do it outside the loop and just use a variable in the inner query? That will prevent context switching and improve speed.
    Edited by: Dave Hemming on Dec 3, 2008 9:34 AM

  • How to write the select query with complex where condition

    Hi all,
    Can u help me in writing  following select query.
    select * from zu1cd_corr where time_stamp between firstday and lastday .
    In the above query time_stamp contains the date and time.
    where as firstday and lastday contains the dates.
    I need to compare the date in the time_stamp with the firstday and lastday.
    But time_stamp contains the time also and it is char of 14 characters length.

    Hi,
    If that is the case u can do as advait specified....
    if the firstday and secondday are select-options then declare two more variables having 14 character length and then concatenate '000000' to firstday variable and '240000' to last day variable and then write ur query.
    CLEAR : lv_firstday,
                 lv_lastday.
    concatenate firstday '000000' to lv_firstday.
    concatenate lastday '240000' to lv_lastday.
    ranges : r_Date for zu1cd_corr-time_stamp.
    r_date-sign = 'I'.
    r_date-option = 'BT'.
    r_Date-low = lv_firstday.
    r_Date-high = lv_lastday.
    append r_date.
    select * from zu1cd_corr  into table it_zu1cd_corr where time_stamp in  r_Date.
    I hope it helps.
    Regards,
    Nagaraj

  • How to frame the select query for wildcard search.

    Hi Experts,
    I have an input field P_USERALIAS.This value could contain the actual value or the wildcard for example : user can enter P_USERALIAS as SAP123 or S or SAPABC123 . I need to generate a dynamic search on table USREFUS  depending on what has been entered.Please help.
    Useful answers will be rewarded.
    Regards,
    Shrita Sharma.

    THIS IS A TEST REPORT FOR WILDCARD SEARCH**
    TABLES: USREFUS.
    PARAMETERS: P_NAME1 TYPE string.
    RANGES: R_NAME1 FOR USREFUS-USERALIAS.
    DATA: T_usrefus LIKE usrefus OCCURS 0 WITH HEADER LINE.
    *replace
    if p_name1 cs '*'.
    replace all occurrences of '*' in p_name1 with '%'.
    SELECT * FROM usrefus
    INTO TABLE T_usrefus
    WHERE useralias like P_NAME1.
    else.
    SELECT * FROM usrefus
    INTO TABLE T_usrefus
    WHERE useralias = p_name1.
    endif.
    LOOP AT T_usrefus.
    WRITE: / T_usrefus-useralias.
    ENDLOOP.
    **THANKS & REGARDS
    SHRITA SHARMA.

  • How to move the selected rows from a  table control in dialog programming

    hiiiiiiii Every1
    I have to update some fields for a slected row in table control on click of a button and save it in database.
    Regards
    Sachin Dhingra

    see below example, I have added INSERT option after DELETE option, you can use same table or you can use differnt table by populating into that table and insert into the db table. If you want to use same internal table then use below code
    LOOP AT itab INTO demo_conn WHERE mark = 'X'.
    insert into table from itab.
    ENDLOOP.
    REPORT demo_dynpro_tabcont_loop_at.
    CONTROLS flights TYPE TABLEVIEW USING SCREEN 100.
    DATA cols LIKE LINE OF flights-cols.
    DATA: ok_code TYPE sy-ucomm,
    save_ok TYPE sy-ucomm.
    DATA: itab TYPE TABLE OF demo_conn.
    TABLES demo_conn.
    SELECT * FROM spfli INTO TABLE itab.
    LOOP AT flights-cols INTO cols WHERE index GT 2.
    cols-screen-input = '0'.
    MODIFY flights-cols FROM cols INDEX sy-tabix.
    ENDLOOP.
    CALL SCREEN 100.
    MODULE status_0100 OUTPUT.
    SET PF-STATUS 'SCREEN_100'.
    ENDMODULE.
    MODULE cancel INPUT.
    LEAVE PROGRAM.
    ENDMODULE.
    MODULE read_table_control INPUT.
    MODIFY itab FROM demo_conn INDEX flights-current_line.
    ENDMODULE.
    MODULE user_command_0100 INPUT.
    save_ok = ok_code.
    CLEAR ok_code.
    CASE save_ok.
    WHEN 'TOGGLE'.
    LOOP AT flights-cols INTO cols WHERE index GT 2.
    IF cols-screen-input = '0'.
    cols-screen-input = '1'.
    ELSEIF cols-screen-input = '1'.
    cols-screen-input = '0'.
    ENDIF.
    MODIFY flights-cols FROM cols INDEX sy-tabix.
    ENDLOOP.
    WHEN 'SORT_UP'.
    READ TABLE flights-cols INTO cols WITH KEY selected = 'X'.
    IF sy-subrc = 0.
    SORT itab STABLE BY (cols-screen-name+10) ASCENDING.
    cols-selected = ' '.
    MODIFY flights-cols FROM cols INDEX sy-tabix.
    ENDIF.
    WHEN 'SORT_DOWN'.
    READ TABLE flights-cols INTO cols WITH KEY selected = 'X'.
    IF sy-subrc = 0.
    SORT itab STABLE BY (cols-screen-name+10) DESCENDING.
    cols-selected = ' '.
    MODIFY flights-cols FROM cols INDEX sy-tabix.
    ENDIF.
    WHEN 'DELETE'.
    READ TABLE flights-cols INTO cols WITH KEY screen-input = '1'.
    IF sy-subrc = 0.
    LOOP AT itab INTO demo_conn WHERE mark = 'X'.
    DELETE itab.
    ENDLOOP.
    ENDIF.
    WHEN 'INSERT'.
    READ TABLE flights-cols INTO cols WITH KEY screen-input = '1'.
    IF sy-subrc = 0.
    LOOP AT itab INTO demo_conn WHERE mark = 'X'.
    itab1 = itab.
    modify itab1.
    ENDLOOP.
    ENDIF.
    if not itab1 is initial.
    INSERT dbtab FROM TABLE itab1.
    endif.
    ENDCASE.
    ENDMODULE.

  • How to highlight the selected value in a table

    Hi All,
    I have list of roles in a table like admin,dba...etc.
    i will select the current selected role using
      Stgin role =wdCotext.currentElement().getRole();
    After getting the role i bind this value in context.
    now my requiremnet is i will navigate to other table view containing all roles like admin,dba,networkadmin .
    I have to highlight the selected role in previous table to new table containing the  all the roles.
    means selected role should be highlight in a next table view list of roles.
    please help.

    Hi mohammad,
    To achieve this functionality, use another integer variable to store the index of the currently selected element in the first view. Pass this variable's value to the next view (either as plug parameter or throgh mapping) and set the Lead selection for the table as this index in the second view.
    In the first View ....
    int n = wdContext.current<your_node>Element().index()
    pass this value from first view to second view.
    In the second view
    wdContext.node<your_node>().setLeadSelection(n)
    Hope this helps,
    Best Regards,
    Nibu.
    Message was edited by: Nibu Wilson

  • How to upload the web query result  to CSV/Text file

    Hi,
    Kindly help me on the following.
    1)       I have info-provider (IP), which has info-objects "company code" and "supplier".
    2)       I built a query by putting company-code with a variable in free-charateristics and supplier-code in row.
    3)       When I run this query, it will ask company-code as input and the result will be filtered using company-code.
    4)       For this query, I created a web-template and assigned data-provider to display the data on the web.
    5)       The user wants to enter input company-code='1000' and write the data in a CSV file in a specific directory. i.e, by clicking the execute button (after entering company code) , the result should go to the CSV or text file. i.e. the application should automatically generate the file with query results.
    Note: The user should not use context menu to EXPORT TO CSV OR EXCEL file.
    Please let me know, if there is any tutorial. Thanks a lot advance help.
    Regards
    Kandasamy

    1. SELECT INTO
    Below method will create table when data is inserted from one table to another table. Its useful when you need exactly same datatype as source table.
    Use AdventureWorks2008R2;
    Go
    ---Insert data using SELECT INTO
    SELECT AddressLine1, City
    INTO BothellAddresses
    FROM Person.Address
    where City = 'Bothell';
    GO
    ---VERIFY DATA
    Select AddressLine1, City
    FROM BothellAddresses
    ---DROP TABLE
    DROP TABLE BothellAddresses
    GO
    2. INSERT INTO SELECT
    Below method will need table to be created prior to inserting data. Its really useful when table is already created and you want insert data from
    another table.
    Use AdventureWorks2008R2;
    Go
    ---Create Table
    CREATE TABLE BothellAddresses (AddressLine1 NVARCHAR(60), City NVARCHAR(30))
    ---Insert into above table using SELECT
    INSERT INTO BothellAddresses(AddressLine1, City)
    SELECT AddressLine1, City
    FROM Person.Address
    where City = 'Bothell';
    ---VERIFY DATA
    Select AddressLine1, City
    FROM BothellAddresses
    ---DROP TABLE
    DROP TABLE BothellAddresses
    GO
    Regards,
    Vishal Patel
    Blog: http://vspatel.co.uk
    Site: http://lehrity.com

  • Insert the MDX Query Data into SSMS Table

    Hi, I'm using below query frequently on SSAS .
    select * from $system.discover_commands
    I want that when this query executed & If any output returns , then that output should be inserted into SSMS
    Table(OLTP DB) .

    Hello,
    You can use a linked server to SSAS to run queries from SQL Server against SSAS cubes and to insert the result into a relational table.
    See e.g.:
    Passing Queries from SQL Server to a Linked Analysis Server
    Querying SSAS with SQL
    Creating a Linked Server for Analysis Services
    Olaf Helper
    [ Blog] [ Xing] [ MVP]

  • How to get the dynamic query result

    If in one query, there is the amount range dimension, based on different dimension value combination, the customer revenue should be refreshed into different range, how to make it by cube?
    eg.
    Customer Store    Material  Month    Amount
    C001     M & S    Tennis    2005/01   "10"
    C001     Douglas  Tennis    2005/02   "60"
    C002     M & S    Soccer    2005/01    "1"
    C002     M & S    Soccer    2005/02    "50"
    C002     M & S    Tennis    2005/02    "50"
    C003     Douglas  Tennis    2005/01    20
    Query condition:
    Time Customer Amount Range     Amount
    2005 C001     0~50_____________0
    2005 C001     51~100___________70
    2005 C001     100 +____________0
    2005 C002     0~50_____________0
    2005 C002     51~100___________0
    2005 C002     100+_____________101
    2005 C003     0~50_____________20
    2005 C003     51~100___________0
    2005 C003     100+_____________0
    However, if I drill down Time into month, the result is total different, I only list the result related to customer C001
    Time     Customer  Amount Range    Amount
    2005/01  C001      0~50____________10
    2005/01  C001      51~100__________0
    2005/01  C001      100 +___________0
    2005/02  C001      0~50____________0
    2005/02  C001      51~100__________60
    2005/02  C001      100 +___________0
    Any good solution on that? Thanks for any input.
    Message was edited by: Lei Shao

    Hi, Sen,
    I used your solution in my infocube and query, where I created a structure with 'between'. However, it is still the simple summation in different amount range.
    Just like the following:
    Sales ORG / Sales Office / Sales Rep / Amount
    East      / Atlanta      / 1001      / 3
    East      / Atlanta      / 1002      / 4
    So the query result is the same:
    S-ORG / S-Office / S-Rep / Amount Range / Amount
    East  / Atlanta  / 1001  / 0~5          / 3
    East  / Atlanta  / 1001  / 5+           / 0
    East  / Atlanta  / 1002  / 0~5          / 4
    East  / Atlanta  / 1002  / 5+           / 0
    When I remove 'drill down' for Sales Rep, the result is:
    S-ORG / S-Office / Amount Range / Amount
    East  / Atlanta  / 0~5          / 7
    East  / Atlanta  / 5+           / 0
    However our expection for the result is different, because in business traction, if we remove sales rep, the sales org and sales office will get the sub-total like this: (we can image it with ABAP program sub-total)
    Sales ORG / Sales Office / Amount
    East      / Atlanta      / 7
    So our expection for the result is:
    S-ORG / S-Office / Amount Range / Amount
    East  / Atlanta  / 0~5          / 0
    East  / Atlanta  / 5+           / 7
    Therefore, any good suggestion for this?
    Thanks a lot
    Regards,
    LS

  • How to Publish the ABAP query results as csv

    Hi,
    I have a scenario and need help for the same, I need to query a table in CRM which has the long text information and publish or save the result as a csv file, is it possible? if so please tell me the steps and code if available
    Thanks
    Akila.R

    Hi,
    Two formats of creating a CSV file:
    report zrich_0001 .
    data: it001 type table of t001 with header line.
    data: iout type table of string .
    data: xout type string.
    field-symbols: <fs>.
    select * into table it001 from t001.
    loop at it001.
      clear xout.
      do.
        assign component sy-index of structure it001 to <fs>.
        if sy-subrc <> 0.
          exit.
        endif.
        if sy-index = 1.
          xout = <fs>.
        else.
          concatenate xout <fs> into xout separated by ','.
        endif.
      enddo.
      append xout to iout.
    endloop.
    call function 'GUI_DOWNLOAD'
         exporting
              filename = 'C:\test.csv'
         tables
              data_tab = iout.
    report ztest.
    type-pools:TRUXS.
    data: begin of itab occurs 0,
          vbeln like vbap-vbeln,
          posnr like vbap-posnr,
          end of itab.
    data:  itab1 type TRUXS_T_TEXT_DATA.
    select vbeln
           posnr
           up to 10 rows
           from vbap
           into table itab.
    CALL FUNCTION 'SAP_CONVERT_TO_CSV_FORMAT'
      EXPORTING
        I_FIELD_SEPERATOR          = ','
      TABLES
        I_TAB_SAP_DATA             = itab
      CHANGING
        I_TAB_CONVERTED_DATA       =  itab1
      EXCEPTIONS
        CONVERSION_FAILED          = 1
        OTHERS                     = 2.
    IF SY-SUBRC <> 0.
      MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    CALL FUNCTION 'GUI_DOWNLOAD'
      EXPORTING
        filename = 'C:\TEMP\TEST.CSV'
      TABLES
        data_tab = itab1
      EXCEPTIONS
        OTHERS   = 1.
    Use SE38.
    Regards
    Subramanian

  • How to open the TFS query results in Excel?

    Hello Guys,
    Question 1: Is there any way to export the query results from the TFS web browser?
    Question 2: Is there any way to export the query results from Team Explorer 2013?
    Here is the query results in TFS:
    How do I export this result in excel for further analysis? 
    I have also connected to Team explorer 2013 and right clicked on the query, but there is no option to open the results in Excel, see below:

    Hello,
    _Pls follow these guide lines for ensuring proper output in Microsoft Excel:
    1.First compare the fields properties and the frames properties between the reports created with wizard and the reports created manually.
    2. Do not leave any space between two adjacent objects.
    Explanation: Because any space, including a few pixels, between two adjacent objects will result in an empty cell or column in Excel output
    3.Make sure that the widths of all objects are vertically consistent.
    Explanation: If the objects are not exactly aligned vertically, that is, have inconsistent widths, it is likely to result in insertion of unwanted cells/columns in Excel.
    4. Pls. Make sure that the vertical elasticity of the frames and repeating frames is not fixed unless you are sure you have allocated enough space to accommodate all the records.
    Explanation: If you set the Vertical Elasticity property of a frame to Fixed, the output in Excel will show only as many records as could appear on the first page of the paper output. Since Excel does not have a page concept, it is not able to overflow the remaining rows to the next page.
    5. For reliable formatting of spreadsheet output, enclose the whole layout area in a frame.
    Explanation: This action prevents the possibility of parallel objects displaying in different vertical positions, one following the other.
    Hope this helps.
    Regards,
    Alex

Maybe you are looking for