How to run a SQL query which is stored in a column using PL/SQL?

Hello
I have a table A and one of the column values is select * from emp where empno :=xyz;
Now I would like to call this SQL query using a cursor in PL/SQL and run this for all the empno's and insert them into a temp table.
Can anybody help me in writing this PL/SQL query?
With Regards,
Mohan

user525114 wrote:
The primary reason for doing this is we are calculating percentiles on an entity sales for different range periods, and there are several sql queries stored in a cloumn, so we would like to know whether we can run these queries by calling them in a pl/sql query, Its not necessary that we need to use a cursor, but once fetching the result set of the query we would like to insert them in a table.Vamsi,
As said in response to Satya, executing dynamic SQL, looping over the result set and inserting the results one by one in a temporary table, is a horribly bad idea. Especially in terms of performance, but also regarding the maintainability of your code. It's just way more complex than necessary.
If you want to calculate percentages, then use analytic or aggregate functions in SQL to do so. If you want to store them, use a single INSERT SELECT statement.
If you want to continue on the same path, use Satya's code and use it inside a loop.
Regards,
Rob.

Similar Messages

  • How to run a SQL statement which is stored inside an SQL Table

    Hello,
    If anyone please help me with the following problem I would be forever grateful
    I have an SQL statement which is stored inside a certain SQL table, I want to use that SQL statement inside my PL/SQL procedure.
    Was thinking of a simple solution of obtaining the SQL statement into an array and then execute it, yet how could I do so exactly with PL/SQL? I've only started playing around with PL/SQL in the last few days.
    Thanks in advance!
    This is how it looks like more or less:
    Displaying result for:
    SELECT TRIM(OBJ_VALU_TXT)
    FROM   OBJ_VALU_DOC
    WHERE  OBJECT_TYPE  = 'FLD'
      AND  OBJECT_CODE  = 15443
      AND  OBJ_VALU_CD  = 'ACR'
    ORDER BYDOC_SEQ_NO
    00001                                                            
    SELECT
    VALUE(MAX(RECEIPT_NO) + 1, :OUT-COMP-FACTOR)
    FROM RECEIPT
    WHERE (RECEIPT_NO BETWEEN
    :OUT-COMP-FACTOR AND :OUT-TO-NUMBER) OR
    (RECEIPT_NO > :OUT-COMP-FACTOR AND
    :OUT-TO-NUMBER = 0)

    Here's a demo of your requirement.
    create table t ( col1 varchar2(200));
    table created
    insert into t values('select * from dual');
    1 row inserted
    declare
    v_col varchar2(200);
    v_val varchar2(200);
    begin
    select col1 into v_col from t;
    execute immediate v_col into v_val;
    dbms_output.put_line(v_val);
    end;
    X
    Using into clause, you can use as many variables as required. But the basic approach reamins the same.
    But storing SQL in DB is not an efficient design.
    Ishan

  • Give me the sql query which calculte the table size in oracle 10g ecc 6.0

    Hi expert,
    Please  give me the sql query which calculte the table size in oracle 10g ecc 6.0.
    Regards

    Orkun Gedik wrote:
    select segment_name, sum(bytes)/(1024*1024) from dba_segments where segment_name = '<TABLE_NAME>' group by segment_name;
    Hi,
    This delivers possibly wrong data in MCOD installations.
    Depending on Oracle Version and Patchlevel dba_segments does not always have the correct data,
    at any time esp. for indexes right after being rebuild parallel (Even in DB02 because it is using USER_SEGMENTS).
    Takes a day to get the data back in line (never found out, who did the correction at night, could be RSCOLL00 ?).
    Use above statement with "OWNER = " in WHERE for MCOD or connect as schema owner and use USER_SEGMENTS.
    Use with
    segment_name LIKE '<TABLE_NAME>%'
    if you like to see the related indexes as well.
    For partitioned objects, a join from dba_tables / dba_indexes to dba_tab_partitions/dba_ind_partitions to dba_segments
    might be needed, esp. for hash partitioned tables, depending on how they have been created ( partition names SYS_xxxx).
    Volker

  • SQL query  which return all the NET SERVICES which are avaiable in tnsname

    hi all
    how to write a sql query which return all the net services which are avaiable in tnsname.ora
    Regards
    s

    Also, tnsnames.ora is stored on the client, and not necessarily on the server; it's possible (and quite likely) that the name I use for a database in my tnsnames.ora could be different from the name you use for the same database; conversely we might use the same name for two different databases.
    Regards Nigel

  • Need SQL Query which saves query results to an excel file

    Hi,
    I am looking for a sql query which saves/ export results of an query to a excel file
    Thanks,
    Chetan

    I am looking for a sql query which saves/ export results of an query to a excel file
    Thanks,
    Chetan
    Options:
    1) You can use
    BCP command to export result to excel
    2) Insert into excel by using OPENROWSET
    3) Use Import and Export Wizard and provide SQL query as source and Excel as destination
    Please refer:
    http://stackoverflow.com/questions/87735/how-do-you-transfer-or-export-sql-server-2005-data-to-excel
    http://www.codeproject.com/Questions/617527/Export-sql-query-result-in-excel-file
    Cheers,
    Vaibhav Chaudhari
    [MCTS],
    [MCP]

  • How to run a search query for a particular folder in KM related to portal

    Hi,
    Can any one tell me the steps for : how to run a search query for a particular folder in knowledge management related to portal.
    Answers will be rewarded.
    Thanks in advance.
    KN
    Edited by: KN on Mar 18, 2008 6:33 AM

    Ok u may not require a coding
    But u req configuration
    U should first make a search option set
    Link: [Search Option set|http://help.sap.com/saphelp_nw04/helpdata/en/cc/f4e77ddef1244380b06fee5f8b892a/frameset.htm]
    Then u need 2 duplicate a KM Command by the name Search From here
    and customize it to include the Search Option that u have created
    Link: [Search from here|http://help.sap.com/saphelp_nw04/helpdata/en/2a/4ff640365d8566e10000000a1550b0/frameset.htm]
    Then in the layout add this command.
    Regards
    BP

  • Can I put a SQL query into a bind variable and then use it to output report

    Hi,
    Can I put a SQL query into a bind variable and then use it to output report?
    I want to create a report and an item "text area" (say P1_TEXT) which can let user to input a SQL query(they are all technical users and knows SQL very well). Then, I use a bind variable (that text area) to store the SQL statement. Then, I add a submit button and I want to use the following to output the report:
    select * from (:P1_TEXT);
    Do you think it is possible to do that? Any known limitations for APEX in this area?
    Thanks a lot,
    Angela

    You can, but make sure it's what you really want to do. Make sure you are VERY familiar with SQL Injection. Most people who know what it is, go out of their way to prevent SQL Injection. You're going out of your way to allow it.
    You can try using &P1_TEXT. instead of bind variable syntax. Bind variables are one of the best ways to prevent SQL Injection, which is why it's not working for you.
    Once again, I strongly urge you to consider the implications of your app, but this suggestion should get it working.
    Tyler

  • Sql query slowness due to rank and columns with null values:

        
    Sql query slowness due to rank and columns with null values:
    I have the following table in database with around 10 millions records:
    Declaration:
    create table PropertyOwners (
    [Key] int not null primary key,
    PropertyKey int not null,    
    BoughtDate DateTime,    
    OwnerKey int null,    
    GroupKey int null   
    go
    [Key] is primary key and combination of PropertyKey, BoughtDate, OwnerKey and GroupKey is unique.
    With the following index:
    CREATE NONCLUSTERED INDEX [IX_PropertyOwners] ON [dbo].[PropertyOwners]    
    [PropertyKey] ASC,   
    [BoughtDate] DESC,   
    [OwnerKey] DESC,   
    [GroupKey] DESC   
    go
    Description of the case:
    For single BoughtDate one property can belong to multiple owners or single group, for single record there can either be OwnerKey or GroupKey but not both so one of them will be null for each record. I am trying to retrieve the data from the table using
    following query for the OwnerKey. If there are same property rows for owners and group at the same time than the rows having OwnerKey with be preferred, that is why I am using "OwnerKey desc" in Rank function.
    declare @ownerKey int = 40000   
    select PropertyKey, BoughtDate, OwnerKey, GroupKey   
    from (    
    select PropertyKey, BoughtDate, OwnerKey, GroupKey,       
    RANK() over (partition by PropertyKey order by BoughtDate desc, OwnerKey desc, GroupKey desc) as [Rank]   
    from PropertyOwners   
    ) as result   
    where result.[Rank]=1 and result.[OwnerKey]=@ownerKey
    It is taking 2-3 seconds to get the records which is too slow, similar time it is taking as I try to get the records using the GroupKey. But when I tried to get the records for the PropertyKey with the same query, it is executing in 10 milliseconds.
    May be the slowness is due to as OwnerKey/GroupKey in the table  can be null and sql server in unable to index it. I have also tried to use the Indexed view to pre ranked them but I can't use it in my query as Rank function is not supported in indexed
    view.
    Please note this table is updated once a day and using Sql Server 2008 R2. Any help will be greatly appreciated.

    create table #result (PropertyKey int not null, BoughtDate datetime, OwnerKey int null, GroupKey int null, [Rank] int not null)Create index idx ON #result(OwnerKey ,rnk)
    insert into #result(PropertyKey, BoughtDate, OwnerKey, GroupKey, [Rank])
    select PropertyKey, BoughtDate, OwnerKey, GroupKey,
    RANK() over (partition by PropertyKey order by BoughtDate desc, OwnerKey desc, GroupKey desc) as [Rank]
    from PropertyOwners
    go
    declare @ownerKey int = 1
    select PropertyKey, BoughtDate, OwnerKey, GroupKey
    from #result as result
    where result.[Rank]=1
    and result.[OwnerKey]=@ownerKey
    go
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • How can we get the image which is stored in clipboard by labview, is there any functions available like text from clip board

    How can we get the image which is stored in clipboard by labview, i can get the text in clipboard by using invoke node directly.but i cannot get the image, is there any functions or vi available.(image is in Png format)

    The Read from Clipboard method is, unfortunately, limited to text. If the clipboard contains an image then you need to use OS-specific functions calls. This is an example program for Windows. It's old, but it should still work.

  • How to publish XML document whose source is stored in clob column

    I have to create simple application:
    in one table are stored some information about XML documents (date of creation, etc.) and the document source itself in one (unfortunatelly clob type) column.
    The point is to anable users finding document(s) and viewing it.
    Using forms I can search and display information about documents. But I have no idea how to publish XML document whose source is stored in clob column.
    I am using Oracle Portal 3.0 on NT.
    Thanks in advance.

    Hi Sergio,
    This link might be helpful:
    http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/apex/r31/apex31nf/apex31blob.htm
    Also refer the BLOB Download Format Mask :
    {message:id=9716335}
    Here I have given the format mask for APEX 4.0, which will slightly differ for 3.2.1 and proposed changes
    in the format mask are:
    1) Format Mask: DOWNLOAD
    2) Content Disposition: Inline
    This will be achieved with it:
    >
    But now, my user would like to know if it´s possible that APEX application can OPEN some of these files stored on this BLOB column WITHOUT download it.
    My user would like to see a hiperlink (or button) that, if pressed/acessed, can open a new page (or a page inside application) with the document. He doesn´t need to edit this oppened file. He only wants to see it.
    >
    Hope it helps!
    Regards,
    Kiran

  • How to Run a Select Query  stored in a Variable

    Hello,
    I have a following requirement:
    Result of one select query on Var1 , result of other select query in Var2 ,
    if Va2 = 'value11' OR Var2 = 'Value2' then Var1 = 'select query'. Now how can I run this SQL query at the end of the Pl/SQL?
    so I'm writing following query for the same:
    DECLARE
    qry nvarchar2(500);
    result nvarchar2(500);
    BEGIN
    select 'select TEXTVAL as "CHARG" FROM TABLE1 WHERE LOC =''[ParameterValue]'' and KEYNAME =''<<REPLACE>>''' INTO qry from dual;
    SELECT CASE WHEN count(RW."CountofBATCH") > 1 then 'Mixing'
    WHEN count(RW."CountofMAT") = 0 then 'None'
    ELSE 'Other'
    END
    INTO result
    FROM TABLENAME2 TT, XMLTable('/Rowsets/Rowset/Row' PASSING TT.XMLCOL
    COLUMNS
    "CountofBATCH" PATH '/Row[CLABS > 0]/CHARG',
    "CountofMAT" PATH '/Row[MATNR = "[Parameter Value]"]/MAT'
    ) AS RW
    where
    TT.PL = '[Parameter Value]' and
    TT.TANK = '[Parametr Value]' ;
    IF result = 'Mixing' OR result = 'None' THEN
    qry := replace( qry , '<<REPLACE>> ' , result);
    else
    qry := 'Nothing';
    END IF;
    This way the variable qry will have select statement. Now How can I run this qry variable to get the output of that select statement in the same query?

    you can use execute immediate if the output of the query is in the single query.
    that is very simple.
    have the query in the signle string and then pass like this
    declare
    qry varchar2(255);
    result varcharf2(2500);
    vempid number :=1;
    begin
    qry:='select empname from emp where empid=:empid';
    execute immediate qry into result using vempid;
    -----now the data result is in result
    end;

  • How to run an update query on results from a spreadsheet

    Hey there,
    I am new to this kinda thing.
    I received a spreadsheet that has 2 tabs, 1 is called SQL Results, and has a ton of data. 1 is called SQL Statement and has a select statement in the first cell.
    I was told to run an update query using the spreadsheet, and was given this:
    = CONCATENATE("Update CARDMEMBERISSUE set CURRSTATUSCD = 'ACT', DATELASTMAINT = sysdate where AGREENBR = ",A2," and MEMBERNBR = ",B2," and ISSUENBR = ",C2,";")
    = CONCATENATE("Insert into CARDMEMBERISSUEHIST (AGREENBR, MEMBERNBR, ISSUENBR, EFFDATETIME, CARDSTATCD, STATREASON, DATELASTMAINT, DATESENT) values (",A2,",",B2,",",C2,",sysdate,'ACT',null,sysdate,null);"
    I am not sure what to do or how to run this.
    This is the what the lines in the spreadsheet look like, including column header, A1 is blank.
    A B C etc
         AGREE NBR      MEMBERNBR ISSUE NBR CURRSTATUSCD PREFIX CARD NBR AGREETYPCD OWNER PERS NBR     EXT CARD      ISSUE DATE     
    2     12          1     44     ISS g     22 22 19/10/2011

    The =concatenate bits are Excel formulae. Assuming they correctly written, they will generate a set of individual sql statements. The first concaenatewill generate a set of update statements against the CardMemberIssue table, and the seond will generate a set of insert statement to the CardMemberIssueHist table.
    You should be able to just paste the generated statements into whatever tool you are using to run sql to execute them. Before you do that though, make sure that you issue:
    alter session set cursor_sharing=force;before pasting anything in.
    john

  • How to run a WMI query to get an element of a class?

    Hello everyone,
    I am trying to run a PowerShell Query to get the value of a certain element inside a class instance. How can I accomplish this?
    I tried this...
    PS C:\windows\system32> Get-WmiObject DCIM_BIOSPassword -Namespace ROOT\DCIM\SYSMAN | Select AttributeName,IsSet
    AttributeName                                                                 IsSet
    AdminPwd                                                                       True
    SystemPwd                                                                     False
    and I get the result of both instances; (Because there are two instances inside the class!) I want the result of just one instance.
    Thank you very much in advance.

    This is the result I get;
    PS C:\windows\system32> Get-WmiObject DCIM_BIOSPassword -Namespace ROOT\DCIM\SYSMAN | Get-Member
    TypeName: System.Management.ManagementObject#ROOT\DCIM\SYSMAN\DCIM_BIOSPassword
    Name MemberType Definition
    PSComputerName AliasProperty PSComputerName = __SERVER
    AttributeName Property string AttributeName {get;set;}
    Caption Property string Caption {get;set;}
    CurrentValue Property string[] CurrentValue {get;set;}
    DefaultValue Property string[] DefaultValue {get;set;}
    Description Property string Description {get;set;}
    ElementName Property string ElementName {get;set;}
    InstanceID Property string InstanceID {get;set;}
    IsOrderedList Property bool IsOrderedList {get;set;}
    IsReadOnly Property bool IsReadOnly {get;set;}
    IsSet Property bool IsSet {get;set;}
    MaxLength Property uint64 MaxLength {get;set;}
    MinLength Property uint64 MinLength {get;set;}
    PasswordEncoding Property uint32 PasswordEncoding {get;set;}
    PendingValue Property string[] PendingValue {get;set;}
    __CLASS Property string __CLASS {get;set;}
    __DERIVATION Property string[] __DERIVATION {get;set;}
    __DYNASTY Property string __DYNASTY {get;set;}
    __GENUS Property int __GENUS {get;set;}
    __NAMESPACE Property string __NAMESPACE {get;set;}
    __PATH Property string __PATH {get;set;}
    __PROPERTY_COUNT Property int __PROPERTY_COUNT {get;set;}
    __RELPATH Property string __RELPATH {get;set;}
    __SERVER Property string __SERVER {get;set;}
    __SUPERCLASS Property string __SUPERCLASS {get;set;}
    ConvertFromDateTime ScriptMethod System.Object ConvertFromDateTime();
    ConvertToDateTime ScriptMethod System.Object ConvertToDateTime();
    But this is not it. I want to get the value of "IsSet" for AdminPwd only.

  • Send SQL query or call stored procedure, which is best???

    hello experts!!
    i would like to ask what will be the best implementation on querying a database using Java, send a SQL query(insert into table values...) or call stored procedure(just pass parameters)?? and also in stored procedure does "autoCommit/rollback" applies/make sense??

    I searched google for this:
    Stored Procedures vs. SQL
    and found this useful link:
    http://www.karlkatzke.com/stored-procedures-vs-sql-calls/
    I thiink you should also read up on other articles based on such google searches
    to get other opinions. Also, read the links provided by that article.
    Personnally, I think stored procedures should be avoided unless there is a definite
    advantage as specified in the above article. Especially not used for CRUD operations.
    Also, no matter where you put the SQL, it should be documented. I've seen too many stored procedures that aren't documented.

  • How to run a BI query from SSM

    HI,
    My client would like to drill down to a BI query where the starting point is a KPI.
    For eg, we have a KPI "Turnover". When we are at kpi detailed level for a specific period, we would like to run a query to have detailed information for turnover (we dont want to use report functionnality of SSM).
    We are using SSM 7.5 and BW queries as data provider.
    Is there a way to achieve this ? (web service ? )
    Thanks in adavnce

    Jacques,
    You cannot run a BI Query from the end user interface of SSM. Your alternatives are to create an associated report inside SSM or use an Associated Link in the KPI Details section.
    Right above the graphing on the KPI detail page there is the link Create Associated Report. SSM has some template reports and allows users to put together a report based on available SSM data.
    There is also the possibility of using Associated Links on the KPI detail page to point the user via a url to another reporting application, though it would not bring that data with it.
    Regards,
    Bob

Maybe you are looking for