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;

Similar Messages

  • How to execute a select query stored in variable

    Hello  helpers ,
    I have some "select queries" stored in the database . Now I can derive this query in some variable . How do I execute this query from the variable .
    example :
    Data Query type char50 .
    QueryVar = 'Select MATNR from MBEW where BWKEY = '0001' . '
    How do I execute this Query stoored in variable QueryVar in ABAP program ?
    Thanks a lot for helping .
    Regards
    Shashank

    Shashank,
    It is also possible to use (column_syntax) and (dbtab_syntax) together with (cond_syntax) when using SELECT statements in ABAP. For more info on (column_syntax) and (dbtab_syntax) just have a quick look at ABAP Keyword documention on SELECT statement (hit F1 on SELECT then scroll down to Select->Select result->Select Columns....)
    So in your case, you need to separate out (split) the value in 'wa_itab-query' into other variables or append into separate internal tables using common keys etc. - then looping at those tables with the common key (READ TABLE WITH KEY....) use the following syntax at the time of triggering the SELECT query:
    SELECT (column_syntax)
           FROM (dbtab_syntax)
           WHERE (cond_syntax).
    Also worth a look at this example below:
    PARAMETERS: p_cityfr TYPE spfli-cityfrom,
                p_cityto TYPE spfli-cityto.
    DATA: BEGIN OF wa,
             fldate TYPE sflight-fldate,
             carrname TYPE scarr-carrname,
             connid   TYPE spfli-connid,
           END OF wa.
    DATA itab LIKE SORTED TABLE OF wa
                   WITH UNIQUE KEY fldate carrname connid.
    DATA: column_syntax TYPE string,
          dbtab_syntax TYPE string.
    column_syntax = `c~carrname p~connid f~fldate`.
    dbtab_syntax = `( ( scarr AS c `
      & ` INNER JOIN spfli AS p ON p~carrid  = c~carrid`
      & ` AND p~cityfrom = p_cityfr`
      & ` AND p~cityto   = p_cityto )`
      & ` INNER JOIN sflight AS f ON f~carrid = p~carrid `
      & ` AND f~connid = p~connid )`.
    SELECT (column_syntax)
           FROM (dbtab_syntax)
           INTO CORRESPONDING FIELDS OF TABLE itab.
    LOOP AT itab INTO wa.
      WRITE: / wa-fldate, wa-carrname, wa-connid.
    ENDLOOP.
    Hope this helps.
    Cheers,
    Sougata.

  • How to run batch select query ?

    I have multiple "select" query .
    how do i run the query in a efficient way and absorp the values into an ArrayList ?
    addbatch() method is mainly used for "insert" kind of query .
    and also , it would be bad idea to run "select:" query one by one .
    can you tell whats the best use ?

    Are your queries related to each other, I mean, do you have something like
    select xpto from someTable where someValue = 1
    select xpto from someTable where someValue = 2
    select xpto from someTable where someValue = 3
    If it's something like this you can group
    select xpto from someTable where someValue in(1,2,3)
    If it is not I think there's no other way but running one at a time.
    mleiria

  • 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

  • How to display a select query record in a tool tip?

    hi,
    How to display a select query record in a tool tip?
    for example i have a report employee. when i move the mouse pointer over a employee name, the tool tip should display the respective department id, department name...of that employee name.
    select dep_id, dep_name ....from department where employee.....Is it possible?
    thanks

    Dear Skud,
    Yes its possible..select ''||ename||'' from emp
    other wise you can use jQuery tooptip or some other JScript bundles.
    Thanks and Regards
    Maheswara

  • 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

  • How to run a SQL Server Stored Procedure

    I need to run a SQL Server Stored Procedure in answer, the stored procedure use a hash table (temporary table) and I nedd to pass a parameter to stored procedure
    anyone know if is it possible in OBIEE, if yes how.
    thank you
    max

    thank you, but I'm not understand what you mean. I need to run this command in answer "direct access database"
    exec storedprocedure 1,1,1
    if I run this I receive thi error:
    error : [nQSError: 16001] ODBC error state: S0002 code: 208 message: [Microsoft][ODBC SQL Server Driver][SQL Server]object name '#TempList' not valid.. [nQSError: 16002] Cannot obtain number of columns for the query result. (HY000).
    here is the code of stored procedure:
    ROC [dbo].[GetOrderListmax]
    @OrderList varchar(500)
    AS
    BEGIN
    SET NOCOUNT ON
    CREATE TABLE #TempList
    OrderID int
    DECLARE @OrderID varchar(10), @Pos int
    SET @OrderList = LTRIM(RTRIM(@OrderList))+ ','
    SET @Pos = CHARINDEX(',', @OrderList, 1)
    IF REPLACE(@OrderList, ',', '') <> ''
    BEGIN
    WHILE @Pos > 0
    BEGIN
    SET @OrderID = LTRIM(RTRIM(LEFT(@OrderList, @Pos - 1)))
    IF @OrderID <> ''
    BEGIN
    INSERT INTO #TempList (OrderID) VALUES (CAST(@OrderID AS int)) --Use Appropriate conversion
    END
    SET @OrderList = RIGHT(@OrderList, LEN(@OrderList) - @Pos)
    SET @Pos = CHARINDEX(',', @OrderList, 1)
    END
    END
    SELECT o.OrderID, CustomerID, EmployeeID, OrderDate
    FROM dbo.Orders AS o
    JOIN
    #TempList t
    ON o.OrderID = t.OrderID
    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.

  • How to write XSJS Select Query with input parameters

    Hello Experts,
    I am creating a xsjs file and in that file I am trying to write a Select Query based on a Calculation View
    I have tried it the following way:
    var query = 'SELECT TOP 100 \"Name\", \"Address\", \"City\", \"Country\" FROM \"_SYS_BIC\".\"Test.HL/AddressView\"'
        + 'WITH PARAMETERS(\'PLACEHOLDER\' = (\'$$P_Name$$\', \' Akhil \'),'
      + '\'PLACEHOLDER\' = (\'$$P_City$$\', \' Lucknow \'))';
    But it gives me the "Mixed spaces and tabs error".
    How should I write XSJS Select Query with input parameters?
    Regards,
    Rohit

    >But it gives me the "Mixed spaces and tabs error".
    Mixed spaces and tabs has nothing to do with the syntax of the statement. You used both spaces and the tab in the content - which JSLint doesn't like.  Remove the beginning spaces of each line and use only one or the other.
    The actual syntax of your statement doesn't look right.  The problem is that you are escaping the \ when you don't need to if you are using ' instead of " for your string.  You escape with \" in the first line but then escape with \' in the 2nd and 3rd line.  That is going to cause serious parsing problems with the command.

  • How to run a pl/sql stored procedure as a concurrent program

    Hi All,
    I created a package PURGE_DEAL_REQUESTS. It contains a procedure QPR_DELETE_CANCELLED_REQUESTS. I want to run this stored procedure as concurrent program in ebs suite....
    Can anyone tell me how to run this procedure as a concurrent program(in ebs suite).....?
    Thanks
    Swathi.

    You need to add the concurrent program to the group of the responsibility that will run the report. For more details, please refer to:
    Note: 73492.1 - Creating a PL/SQL Concurrent Program in Oracle Applications
    https://metalink2.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=73492.1
    Note: 133991.1 - How to Register a Custom Report
    https://metalink2.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=133991.1

  • How to create a select query to compare a collection via jpa?

    I'm new to jpa (java persistence) and its query language.
    If I've an entity named "Person" with a collection of Addresses (a one-to-manay relationahip), how do I create a Select query to get a person by using a collection of Addresses as its input parameter?
    Would "SELECT p FROM Person p JOIN p.addresses = :addresses" work?

    Hi,
    You can try the below logic:
    STATISTICS.date_reg} >= '27-may-2011' and { STATISTICS.date_reg} < ' 27-June-2011'
    I guess you are trying to apply this condition.
    Here in selection formula you need not to give select and from.
    Cheers,
    Kiran

  • How to month in select query.....for vbap

    Hi Experts,
    I am using selection option Listbox ( January, February, March, etc...).
    How to use it in select query for table vbap (Shown below),
    I want to retrieve data of january from vbap and matches erdat in pa_mnr.
        parameters: pa_mnr type ztemp-zlist as listbox visible
                    length 13 default 'January'.
        select * from vbap into corresponding fields of table it_vbap
                 where matnr in matnr1 and
                       gsber = 'HIP'   and
                       vstel = 'BSP'   and
                       erdat in pa_mnr.

    hi,
    take the date from the select option.
    let say you have date, month and year seperate select option..
    then look at some FM whcih gives month number for your month name..
    concatenate all the three separated by dot and put it in a variable of type datum..
    now your variable contains the user selected date.
    you can write your select query.
    rewards if useful
    regards,
    nazeer

  • How to run recordset SQL query in FORM DATA event

    How can I run recordset SQL query in FORM DATA event upon clicking on Add button in the document?

    Hi Slamet,
    When you receive a form data event you have a class containing inside it a ObjectKeys xml info regarding the object added/modified,...
    With the objects keys you can then use the DI API method called GetByKeys to obtain the DI Object.
    There is some information about it in the SDK Help file, mainly in the "FormDataEvent" class definition:
    <i>The event provides the unique ID (BusinessObjectInfo.ObjectKey) of the modified business object. You can use the value of this property as an input parameter in the DI API DataBrowser.GetByKeys method to get a DI object.</i>
    Pay attention you don't have this information in the Before=True event of the Add as it is not yet in the database.
    Hope it helps
    Trinidad.

  • How to run a select count(*) with multiple rows returned

    Hi,
    I have to run a select count(*) for different reports.
    1) Select count(*) from table
    where state = 'CA'
    2) Select count(*) from table
    where state = 'NY'
    3) Select count(*) from table
    where state = 'NV'
    Instead of running this query again for 50 times, is there a way for me to just put it in one query and get multiple row returns? Thank you.

    Samantha wrote:
    Hi,
    I have to run a select count(*) for different reports.
    1) Select count(*) from table
    where state = 'CA'
    2) Select count(*) from table
    where state = 'NY'
    3) Select count(*) from table
    where state = 'NV'
    Instead of running this query again for 50 times, is there a way for me to just put it in one query and get multiple row returns? Thank you.select state, count(*) from table group by state order by 1;

Maybe you are looking for

  • When a tab is close, firefox next shows the tab to the right. How do I get firefox to show the tab to the LEFT of the closed tab?

    I have 3 tabs open named 1, 2 and 3. If I close tab 2, Firefox will automatically show tab 3. How do I get Firefox to show tab 1 instead of tab 3? Basically, move to the left instead of the right? I searched about:config using words like: tab, open,

  • How to save Checkbox inputs as a Variants in WD ABAP

    Hi, I am going through this nice blog [http://www.sdn.sap.com/irj/scn/weblogs;jsessionid=(J2EE3414700)ID0832150950DB20043138143752756391End?blog=/pub/wlg/10731] which helped me creating varaint options for SELECT -optins fields. Everything works fine

  • Mass processing of TO

    Hello all, I have a client scenario, in which picking is done. i want to know any SAP fuctionality that exists for mass processing of TOs. IF so, pl. post it the t-code and the procedure. Thanks, Maxx

  • ERROR WHEN RUNNING B.D.C FOR ASSIGN OF INSPECTION PLAN TO MATERIALS

    HI GURUS, WHEN I RUN B.D.C TO ASSIGN INSPECTION PLAN TO MATERIAL I AM GETTING THE FOLLOWING ERROR. Error occurred when checking type  group . Message no. CP852 Diagnosis Errors occurred when checking the routing. Procedure u2022     If the check occu

  • Error Message on Updates??

    I have downloaded a couple of updates in the last two days from the App Store one for Safari and one for iTunes, at the end of each one I got this error pop up. The system extension "/System/Library/Extensions/AppUSBthernetHost.kext" was installed im