Execute dynamic query stored as varchar in a different table.

Hi,
I have a table with a column as query,which stores the query i want to fire.for eg.my query will be like :-
Select name,empid from employees where name =null
Now,I have a stored procedure in which i have declared  a variable @query .I want to replace the following line of code .
if exists(Select name ,empid from employees where name=null)
begin
--send mail
end
as
if exists(@query)
But it doesnt seem to work because it is taking the @query as varchar and not an actual t-sql command.I want to keep the query dynamic as each row in my table has a different query to fire.

And only to clarify Praveen's solution:
DECLARE @DynamicSQl nvarchar(250), @x nvarchar(100)
SELECT @x = '@retVal int output'
DECLARE @retVal int
SET @DynamicSQl = 'SET @retVal = CASE WHEN EXISTS (' + @query + ') THEN 1 ELSE 0 END'
EXEC sp_executesql @DynamicSQl, @x, @retVal output
IF @retVal > 0
BEGIN
print 'send mail'
END
However, Nimo should probably have some error handling, as the stored query may not be syntactically correct. And even if it is syntactically correct, it may not play well with EXISTS. Case in point: a query that starts with a CTE.
And of course, if any user is permitted to add these queries, and this code is exeuted with high permissions, they can inject queries that perform evil things they don't have permissions to do themselves, so be careful.
Erland Sommarskog, SQL Server MVP, [email protected]

Similar Messages

  • Executing a query stored ina file

    Hello all,
    I need to execute a query stored in a file through pl/sql program
    for eg: i have a query "select sysdate from dual;" stored in a file date.sql. this file is kept under default location oracle/bin directory. this has to be done through a plsql program . How can i achieve this
    Regards,
    Kiran

    we cannot execute a query stored in a file through pl/sql program. Instead use UTL package to read the script (in which seprate the script using ';' as delimiter or new line) and assign it to a variable in pl/sql program, then use the execute immediate command to execute the SQL.
    or store the required script in a procedure, call the SP in plsql program.
    Twinkle

  • Need to execute Dynamic query for the report

    I was wondering if we can have the option of choosing at runtime from the report builder parameter so that if the end-user selects 'Yes' then the report will run one specific query and if he chooses 'No' then another particular query is invoked. What I mean to say that by choosing between Yes and No at runtime one should have the option of returning query results based on the same table but having different columns selected via the SELECT statement
    means we have two querires on our report & upon the chosen parameter we should execute only one of them ... wht should i do to apply tht ???

    As the previous post noted lexicals are a terrific way to accomplish dynamic queries in Oracle reports.
    Another way you could accomplish this would be to use a UNION, whereas the first select in the UNION represents one user option, then second query represents the second option.
    For example:
    SELECT customer_name name, customer_address address
    FROM customer_table
    WHERE :p_choice = 'Customer Info'
    UNION
    SELECT employee_name name, employee_address address
    FROM employee_table
    WHERE :p_choice = 'Employee Info'If when running the report, the user chooses 'Customer Info' the first query would return results, if the user chose 'Employee Info' then just information from the second query would return information.
    So there are different ways to accomplish what you are looking for, you just need to find which is going to work best for you.
    Hope this helps!

  • How to execute sql query stored in  a variable

    Hi
    define query = 'select * from abc;'
    then how to execute this defined variable query.
    Thanks,
    Shyam

    EXECUTE IMMEDIATE mmy_sql --(variable
    INTO     mmy_default_bill_type;
    by kumar.

  • TSQL - Dynamic Query Case statment update issue - to update table by left shifting the rows

    Hi all
    I need an help on my tsql query in 2000 to fix the case statement.
    I have a table like shown below.
    On this table where ever I see PortID as 101 and 105 I need to remove it and shift the rows from right to left.
    ie on First row PortID1 is 101 so I need to remove it and replace it with PortId2 and similarly PortID2 replaced my PortID3 and so on.
    ie like on excel if you delete cell we need to shift the rows to left .
    I wrote an dynamic update statement i,m not sure on the assigning dynamic case statment.
    CREATE TABLE [TravelRank]
    [Destination] [varchar] (50) NULL,
    [PortID1] [int] NULL ,
    [Distance1] [int] NULL ,
    [Rating1] [int] NULL ,
    [PortID2] [int] NULL ,
    [Distance2] [int] NULL ,
    [Rating2] [int] NULL ,
    [PortID3] [int] NULL ,
    [Distance3] [int] NULL ,
    [Rating3] [int] NULL ,
    [PortID4] [int] NULL ,
    [Distance4] [int] NULL ,
    [Rating4] [int] NULL
    INSERT into [TravelRank]
    select 'Virgin Islands','101','10','5','102','20','5','103','31','5','109','41','5'
    Union all
    select 'Guinea','101','15','3','102','22','3','105','32','2','110','45','4'
    Union all
    select 'Benin ','102','12','4','106','28','4','104','33','3','109','48','2'
    Union all
    select 'Ecuador','102','18','5','101','29','5','108','34','1','111','45','5'
    Union all
    select 'Belarus ','103','17','4','105','24','4','108','45','4','112','46','3'
    Union all
    select 'Cook Islands','105','11','2','108','23','2','101','32','2','107','42','4'
    Here is my code to fix
    declare @SQL varchar(4000)
    declare @left varchar(1)
    declare @right varchar(1)
    select @left = '1',@right = '2'
    while @left < 4
    begin
    select @SQL = '
    update t1.PortID' + @left + ' = t2.PortID' + @right + '
    t1.Distance' + @left + ' = t2.Distance' + @right + '
    t1.Rating' + @left + ' = t2.Rating' + @right + '
    'case @left
    when '1' then
    ' t1.PortID' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.PortID' + cast(cast(@right as int)+1 as varchar(1)) +'
    t1.PortID' + cast(cast(@left as int)+2 as varchar(1)) + ' = t2.PortID' + cast(cast(@right as int)+2 as varchar(1)) +'
    t1.PortID' + cast(cast(@left as int)+3 as varchar(1)) + ' = t2.PortID' + cast(cast(@right as int)+3 as varchar(1)) +'
    t1.Distance' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.Distance' + cast(cast(@right as int)+1 as varchar(1)) +'
    t1.Distance' + cast(cast(@left as int)+2 as varchar(1)) + ' = t2.Distance' + cast(cast(@right as int)+2 as varchar(1)) +'
    t1.Distance' + cast(cast(@left as int)+3 as varchar(1)) + ' = t2.Distance' + cast(cast(@right as int)+3 as varchar(1)) +'
    t1.Rating' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.Rating' + cast(cast(@right as int)+1 as varchar(1)) +'
    t1.Rating' + cast(cast(@left as int)+2 as varchar(1)) + ' = t2.Rating' + cast(cast(@right as int)+2 as varchar(1)) +'
    t1.Rating' + cast(cast(@left as int)+3 as varchar(1)) + ' = t2.Rating' + cast(cast(@right as int)+3 as varchar(1)) +'
    ' when '2' then
    ' t1.PortID' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.PortID' + cast(cast(@right as int)+1 as varchar(1)) +'
    t1.PortID' + cast(cast(@left as int)+2 as varchar(1)) + ' = t2.PortID' + cast(cast(@right as int)+2 as varchar(1)) +'
    t1.Distance' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.Distance' + cast(cast(@right as int)+1 as varchar(1)) +'
    t1.Distance' + cast(cast(@left as int)+2 as varchar(1)) + ' = t2.Distance' + cast(cast(@right as int)+2 as varchar(1)) +'
    t1.Rating' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.Rating' + cast(cast(@right as int)+1 as varchar(1)) +'
    t1.Rating' + cast(cast(@left as int)+2 as varchar(1)) + ' = t2.Rating' + cast(cast(@right as int)+2 as varchar(1)) +'
    ' when '3' then
    ' t1.PortID' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.PortID' + cast(cast(@right as int)+1 as varchar(1)) +'
    t1.Distance' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.Distance' + cast(cast(@right as int)+1 as varchar(1)) +'
    t1.Rating' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.Rating' + cast(cast(@right as int)+1 as varchar(1)) +'
    ' when '3' then
    ' t1.PortID' + @left + ' = null '
    t1.Distance' + @left + ' = null '
    t1.Rating' + @left + ' = null '
    else '' end'
    from [TravelRank] t1
    inner join [TravelRank] t2
    on t1.destination = t2.destination
    where t1.PortID1 = 101'
    print @SQL
    -- exec (@SQL)
    select @left = cast(cast(@left as int) + 1 as varchar(1))
    , @right = cast(cast(@right as int) + 1 as varchar(1))
    end
    Thanks a lot in advance.

    declare @SQL varchar(4000)
    declare @left varchar(1)
    declare @right varchar(1)
    select @left = '1',@right = '2'
    while @left < 4
    begin
    select @SQL = '
    update t1.PortID' + @left + ' = t2.PortID' + @right + '
    t1.Distance' + @left + ' = t2.Distance' + @right + '
    t1.Rating' + @left + ' = t2.Rating' + @right + '
    '+CASE @left
    when '1' then
    ' t1.PortID' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.PortID' + cast(cast(@right as int)+1 as varchar(1)) +'
    t1.PortID' + cast(cast(@left as int)+2 as varchar(1)) + ' = t2.PortID' + cast(cast(@right as int)+2 as varchar(1)) +'
    t1.PortID' + cast(cast(@left as int)+3 as varchar(1)) + ' = t2.PortID' + cast(cast(@right as int)+3 as varchar(1)) +'
    t1.Distance' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.Distance' + cast(cast(@right as int)+1 as varchar(1)) +'
    t1.Distance' + cast(cast(@left as int)+2 as varchar(1)) + ' = t2.Distance' + cast(cast(@right as int)+2 as varchar(1)) +'
    t1.Distance' + cast(cast(@left as int)+3 as varchar(1)) + ' = t2.Distance' + cast(cast(@right as int)+3 as varchar(1)) +'
    t1.Rating' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.Rating' + cast(cast(@right as int)+1 as varchar(1)) +'
    t1.Rating' + cast(cast(@left as int)+2 as varchar(1)) + ' = t2.Rating' + cast(cast(@right as int)+2 as varchar(1)) +'
    t1.Rating' + cast(cast(@left as int)+3 as varchar(1)) + ' = t2.Rating' + cast(cast(@right as int)+3 as varchar(1)) +'
    ' when '2' then
    ' t1.PortID' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.PortID' + cast(cast(@right as int)+1 as varchar(1)) +'
    t1.PortID' + cast(cast(@left as int)+2 as varchar(1)) + ' = t2.PortID' + cast(cast(@right as int)+2 as varchar(1)) +'
    t1.Distance' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.Distance' + cast(cast(@right as int)+1 as varchar(1)) +'
    t1.Distance' + cast(cast(@left as int)+2 as varchar(1)) + ' = t2.Distance' + cast(cast(@right as int)+2 as varchar(1)) +'
    t1.Rating' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.Rating' + cast(cast(@right as int)+1 as varchar(1)) +'
    t1.Rating' + cast(cast(@left as int)+2 as varchar(1)) + ' = t2.Rating' + cast(cast(@right as int)+2 as varchar(1)) +'
    ' when '3' then
    ' t1.PortID' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.PortID' + cast(cast(@right as int)+1 as varchar(1)) +'
    t1.Distance' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.Distance' + cast(cast(@right as int)+1 as varchar(1)) +'
    t1.Rating' + cast(cast(@left as int)+1 as varchar(1)) + ' = t2.Rating' + cast(cast(@right as int)+1 as varchar(1)) +'
    ' when '3' then
    ' t1.PortID' + @left + ' = null '+
    ' t1.Distance' + @left + ' = null '+
    ' t1.Rating' + @left + ' = null '
    else '' END + '
    from [TravelRank] t1
    inner join [TravelRank] t2
    on t1.destination = t2.destination
    where t1.PortID1 = 101'
    print @SQL
    -- exec (@SQL)
    select @left = cast(cast(@left as int) + 1 as varchar(1))
    , @right = cast(cast(@right as int) + 1 as varchar(1))
    end
    You were missing a couple of concats. This runs now, but I'm not completely sure if it's the output you were expecting.

  • Query to pull data from 2 different tables

    Hi so currently I am using VS2008 and am using a DNN module to pull information based on a specific Article on our website. On the home page I am currently displaying the Title, Summary, Date and Author of the article. Currently under our feature Stories section of the site http://prepsonthenet.com/dnn/Home/tabid/386/Default.aspx the Title, Summary and Date, Author are being displayed for the top 8 articles that contain images. I was able to combine the 'Author' and Article table to display the 'AuthorName' for the first 8 images. That code is below:
    strQueryArticleFirst.Append("select top 4 ArticleID,Title,Summary,[Text],");
    strQueryArticleFirst.Append("(SELECT NAME FROM AUTHOR AU WHERE AU.AUTHORID = Article.AUTHORID) AS AUTHORNAME, ");
    strQueryArticleFirst.Append("Convert(varchar(50),date,110)as [Date] from article");
    strQueryArticleFirst.Append(" WHERE CategoryID=27 AND State='WI' AND deleted is null ");
    Within this we have a strQueryArticleSecond which displays the next 6 stories without images: http://prepsonthenet.com/dnn/Home/tabid/386/Default.aspx
    The code is a bit different here though and I can't seem to figure out how to link this back up to grab the 'AuthorName'
    strQueryArticleSecond.Append("SELECT * FROM(");
    strQueryArticleSecond.Append("select top 4 * from( ");
    strQueryArticleSecond.Append("select top 8 * from article ");
    strQueryArticleSecond.Append("where CategoryID=27 AND State='WI' and deleted is null ");
    I get what the strQueryArticleSecond and how it is grabbing all the fields that were used in strQueryArticleFirst. I am just wondering how to re-link the AuthorName is this strQueryArticleSecond. Any help is appreciated. Thanks!

    Sarangan,
    Is there a way to get these data in a single
    select query.Yes, use the "union" operator. See the "Oracle SQL Reference" for more details. It is available from here:
    http://tahiti.oracle.com
    Good Luck,
    Avi.

  • Dynamic Query Doubt

    Hi,
    I need to write a Dynamic Query to get the data from the table by using the Input date parameters.
    LIke,
    SELECT* from table where date_start between to_date('12-14-2004','mm-dd-yyyy') AND
    to_date('12-15-2005','mm-dd-yyyy');
    How can i write the above query in dynamic sql as i will get the two dates as input in my procedure
    Help me in this

    Or more preferably use bind variables with the
    EXECUTE IMMEDIATE as, if the query will be called
    many times, the bind variables will prevent hard
    parsing of the statement each time (i.e. it will be
    quicker to execute).blushadow,
    Yes, the execute immediate using bind variables is better/faster than not using bind variables, but your first example outperforms your second one. This is due to the fact that execute immediate really closes all cursors, and in your first example the cursors are kept open (yes, even though you issue a CLOSE cur_test) in the PL/SQL cursor cache.
    SQL> create table i_links
      2  as
      3  select sysdate - l linkdate from (select level l from dual connect by level <= 10000)
      4  /
    Tabel is aangemaakt.
    SQL> exec dbms_stats.gather_table_stats(user,'I_LINKS')
    PL/SQL-procedure is geslaagd.
    SQL> create or replace procedure test1 (start_date in date, end_date in date) as
      2    CURSOR cur_test IS
      3      SELECT count(*)
      4      FROM   i_links
      5      WHERE  linkdate BETWEEN start_date AND end_date;
      6    v_count NUMBER;
      7  begin
      8    OPEN cur_test;
      9    FETCH cur_test INTO v_count;
    10    CLOSE cur_test;
    11    --DBMS_OUTPUT.PUT_LINE('Count: '||v_count);
    12  end;
    13  /
    Procedure is aangemaakt.
    SQL> create or replace procedure test2 (start_date in date, end_date in date) as
      2    v_count NUMBER;
      3  begin
      4    EXECUTE IMMEDIATE 'SELECT count(*) FROM i_links WHERE linkdate BETWEEN :x1 AND :x2' INTO v_count USING start_date, end_date;
      5    --DBMS_OUTPUT.PUT_LINE('Count: '||v_count);
      6  end;
      7  /
    Procedure is aangemaakt.
    SQL> begin
      2    -- warm up
      3    test1(sysdate-365,sysdate);
      4    test2(sysdate-365,sysdate);
      5    -- begin test
      6    runstats_pkg.rs_start;
      7    for i in 1..1000
      8    loop
      9      test1(sysdate-365,sysdate);
    10    end loop;
    11    runstats_pkg.rs_middle;
    12    for i in 1..1000
    13    loop
    14      test2(sysdate-365,sysdate);
    15    end loop;
    16    runstats_pkg.rs_stop(100);
    17  end;
    18  /
    Run1 draaide in 341 hsecs
    Run2 draaide in 348 hsecs
    Run1 draaide in 97,99% van de tijd
    Naam                                                    Run1      Run2  Verschil
    STAT.session cursor cache hits                             0       998       998
    STAT.opened cursors cumulative                             0     1,000     1,000
    STAT.parse count (total)                                   0     1,000     1,000
    LATCH.shared pool                                      1,047     3,043     1,996
    STAT.recursive calls                                   3,001     1,001    -2,000
    LATCH.library cache pin allocation                         8     2,011     2,003
    LATCH.library cache pin 2,048 6,044 3,996
    LATCH.library cache 2,056 6,060 4,004
    Run1 latches totaal versus run2 -- verschil en percentage
          Run1      Run2  Verschil     Pct
        48,522    60,548    12,026  80.14%
    PL/SQL-procedure is geslaagd.Regards,
    Rob.

  • Dynamic query exception

    How to handle dynamic query exception
    in my dynamic query say if i pass the wrong table name it is showing some errors instead i would like to use my own error statement as output
    eg:
    mytable :test_table
    declare mytable varchar2 :=test_table1234 --(which is not present in DB)
    begin
    execute immediate ('select * from '|| mytable);
    -- Error handling here
    end;

    I wouldn't use WHEN OTHERS, not unless you want to be fired for breaking coding standards. If you insist, at least follow it with RAISE.
    Here is a an exposition of the problem, http://www.orafaq.com/wiki/WHEN_OTHERS and another http://tkyte.blogspot.co.uk/2008/06/when-others-then-null-redux.html

  • 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.

  • Query a stored procedure that exec's a dynamic query. Error Linked server indicates object has no columns

    I have a stored procedure that dynamically creates a pivot query.  The procedure works and returns the correct data.  Now I have a requirement to show this data in reporting system that can only pull from a table or view.  Since you can not
    create a dynamic query in a view I tried to do a select from using openquery. 
    Example 'Select * from OpenQuery([MyServername], 'Exec Instance.Schema.StoredProcedure')
    I get the error back "the linked server indicates the object has no columns".  I assume this is because of the first select statement that is stuffing the variable with column names. 
    CODE FROM PROCEDURE
    Alter PROCEDURE [dbo].[Procedure1]
    AS
    BEGIN
    SET NOCOUNT ON
    Declare @cols nvarchar(2000),
      @Tcols nvarchar(2000),
      @Sql nvarchar (max)
    select @cols = stuff ((
          Select distinct '], ['+ModelName + '  ' + CombustorName
           from CombustorFuel cf
           join Model m on cf.modelid = m.modelid
           join Combustors cb on cf.CombustorID = cb.CombustorID
           where cf.CombustorID > 0
           for XML Path('')
          ),1,2,'')+']'
    Set @Tcols = replace(@Cols, ']', '] int')
    --Print @Tcols   
    --Print @Cols
    Set @Sql = 'Select GasLiquid, FuelType, '+ @Cols +'
    from
     Select GasLiquid, FuelType, ModelName+ ''  '' +CombustorName ModelCombustor, CombFuelStatus+''- ''+CombFuelNote CombFuelStatusNote
      from Frames f
      join Family fa on f.Frameid = fa.frameid
      join Model m on fa.FamilyID = m.FamilyID
      join CombustorFuel cf on m.Modelid = cf.modelid
      Join Combustors c on cf.CombustorId = c.CombustorID
      join FuelTypes ft on cf.FuelTypeID = ft.FuelTypeID
      where cf.CombustorFuelID > 0
        and CombustorName <> ''''
     ) up
    Pivot
     (max(CombFuelStatusNote) for ModelCombustor in ('+ @Cols +')) as pvt
    order by FuelType'
    exec (@Sql)

    Then again, a good reporting tool should be able to do dynamic pivot on its own, because dynamic pivoting is a presentation feature.
    SSRS Supports dynamic columns: Displaying Dynamic Columns in SSRS Report
    SQL Reporting Services with Dynamic Column Reports
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014
    Displaying and reading are two very different things.
    #1) SSRS Needs a fixed field list on the input side to know what what to make available in the designer.
    #2) SSRS cant read "exec (@Sql)" out of a proc, even if there is a fixed number of columns (at
    least it can't use it to auto build the field list from the proc)
    I use dynamic SQL in my report procs on a fairly regular basis and I've found it easiest to simply dump
    the results of my dynamic sql into a temp table at the end of the procs and then select from the temp table.
    Basically, Erland is correct. Stop trying to pivot in the query and let SSRS (or whatever reporting software you're using) handle it with a Martix.
    Jason Long

  • Executing a dynamic query in CLOB

    We are storing the sql query in a CLOB object(as the query can grow very big)
    we want to open a cursor based on the query stored in the CLOB object, we have used the following statement
    OPEN cur_get_result FOR TO_CHAR(l_sql_query);
    FETCH cur_get_result BULK COLLECT INTO l_get_result;
    CLOSE cur_get_result;
    to get the result set from the query in to a collection object.
    we are getting the error as
    ORA-22835: Buffer too small for CLOB to CHAR or BLOB to RAW conversion (actual: 5156, maximum: 4000)
    please give us your inputs to solve the above problem.

    > The query will go beyond 32K in size. We are getting
    this error when the query reaches beyond 32K. Is
    there anyway to handle this situation?
    Yes. You borrow my lead pipe and beat the <insert word here> out of the person(s) who decided that designing and coding and implementing a 32+ KB dynamic SQL is the right thing to do.
    I have dealt with some pretty large and complex SQLs through the years. But over 32KB worth of DYNAMIC SQL!? That is a maintenance nightmare. How on earth can that be debugged for runtime errors? Or tuned for performance?
    Something are... well, just plain silly IMO. And a 32+ KB dynamic SQL statement is one of them.
    > Any kind of help would be appreciated.
    I would rethink this approach - kneejerk reaction that this must be a design flaw. Even if not, I would implement this as a mix of SQL and PL/SQL code to modularise it, in order to get a handle on performance and debugging and maintenance issues.
    Er.. sorry if I'm a bit blunt here, but heck.. a 32+ KB dynamic SQL is a prime candidate for a Guinness Book of Records award and a top spot in oracle-wtf.blogspot.com. :-)

  • Stored Procedures - Executing a query with multiple variables

    Hello everyone..
    During development I faced the followng problem. When I tried to execute a query in a stored procedure using 2 or more variables an unexplained error came up! The fact is that I use a form that calls this particular stored procedure using 2 variables.
    Does anybody know why is this happenning?
    Thanx!

    To better help you, could you provide the procedure (or part of it) and the query causing the error?
    Hello everyone..
    During development I faced the followng problem. When I tried to execute a query in a stored procedure using 2 or more variables an unexplained error came up! The fact is that I use a form that calls this particular stored procedure using 2 variables.
    Does anybody know why is this happenning?
    Thanx!

  • Display results from dynamic query created and executed inside procedure

    Hi;
    I have created this code:
    CREATE OR REPLACE PROCEDURE RunDynamicQuery(Var1 IN VARCHAR2, Var2 IN VARCHAR2, VAR3 IN VARCHAR2) AS
    -- Do something
    -- That ends up with a variable holding a query.... (just an example)
    MainQuery :='select sysdate from dual';
    end RunDynamicQuery;
    How can I run this procedure and see the result on the dymanic query generated inside it?
    BEGIN
    compare_tables_content('VAR1','VAR2','VAR3');
    END;
    Expected Output for this given example:
    20-05-2009 11:04:44 ( the result of the dymanic query inside the procedure variable MainQuery :='select sysdate from dual';)
    I tested with 'execute immediate':
    CREATE OR REPLACE PROCEDURE RunDynamicQuery(Var1 IN VARCHAR2, Var2 IN VARCHAR2, filter IN VARCHAR2) AS
    -- Do something
    -- That ends up with a variable holding a query.... (just an example)
    MainQuery :='select sysdate from dual';
    execute immediate (MainQuery );
    end RunDynamicQuery;
    BEGIN
    compare_tables_content('VAR1','VAR2','VAR3');
    END;
    Output:"Statement processed'' (no sysdate displayed ! )
    Please consider that the collums in the query are always dynamic... PIPELINE Table would not work because I would need to define a container, example:
    CREATE OR REPLACE TYPE emp_tabtype AS TABLE OF emp_type;
    FUNCTION RunDynamicQuery (p_cursor IN sys_refcursor)
    RETURN emp_tabtype PIPELINED
    IS
    emp_in emp%ROWTYPE;
    BEGIN
    LOOP
    FETCH p_cursor
    INTO emp_in;
    EXIT WHEN p_cursor%NOTFOUND;
    PIPE ROW (...)

    That would be a nice solution, thanks :)
    ''For now'' I implemented like this:
    My dynamic query now returns a single string ( select col1 || col2 || col3 from bla)
    This way I don't have dynamic collumns issue, and from business side, this ''string'' format works for them.
    This way I can use the pipelines to get the result out...
    OPEN myCursor FOR MainQuery;
    FETCH myCursor
    INTO myRow;
    WHILE (NOT myCursor%notFound) LOOP
    PIPE ROW(myRow);
    FETCH myCursor
    INTO myRow;
    END LOOP;
    CLOSE myCursor;

  • Dynamic Query having IN Clause with VARCHAR parameters

    My query is like this -
    SELECT * FROM TABLE1 WHERE parm1 IN ('v1','v2',v3');
    Now I want to write this as dynamic query as input is coming as csv value -
    ip varchar2(500)
    ip:= 'v1,v2,v3';
    How to write this query now ??
    I take variables -
    sqlQry VARCHAR2(4000)
    sqlQry:= 'SELECT * FROM TABLE1 WHERE parm1 IN ' ¦¦ ip -- this will not work
    pls help
    thnx
    D

    Hi,
    When doing some dynamic SQL it is always a good idea to output the generated SQL just to make sure it is well formed.
    For example doing dbms_output.put_line('sqlQry : '||sqlQry);instead of executing it.
    In your case, you would have noticed that the generated SQL would look like : SELECT * FROM TABLE1 WHERE parm1 IN v1,v2,v3Where the parenthesis around the in-list are lacking, and the values are not between quotes :
    Changing your lines to : (...)
    ip:= '''v1'',''v2'',''v3''';
    sqlQry:= 'SELECT * FROM TABLE1 WHERE parm1 IN (' || ip ||')' ; should allow it to work.

  • Parameter index move while executing PL/SQL stored procedure/function

    Hello, community.
    Have a question for you. It looked like very easy to write some small JDBC-wrapper to handle stored procedure/functions call for Oracle.
    Here is the code snippet of it:
    import java.io.Serializable;
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.util.HashMap;
    import java.util.Iterator;
    import javax.sql.DataSource;
    import oracle.jdbc.driver.OracleTypes;
    import org.apache.log4j.Logger;
    public class SmallHelper {
         public static final int CALL_TYPE__PROCEDURE = 1;
         public static final int CALL_TYPE__FUNCTION = 2;
         public static final int PARAMETER__IN = 1;
         public static final int PARAMETER__OUT = 2;
         private static final Logger log = Logger.getLogger(SmallHelper.class);
         private Connection con = null;
         private CallableStatement statement = null;
         private String name;
         private int type;
         private int resultType;
         private HashMap arguments = new HashMap();
          * Creates connection using data source as parameter.
          * @param ds - data source
          * @throws EhlApplicationException
         public SmallHelper(DataSource ds) throws Exception {
           try {
                   con = ds.getConnection();
              catch (SQLException e) {
                   ExceptionHelper.process(e);
         public void registerProcedure(String name) {
              this.name = name;
              this.type = CALL_TYPE__PROCEDURE;
         public void registerFunction(String name, int resultType) {
              this.name = name;
              this.resultType = resultType;
              this.type = CALL_TYPE__FUNCTION;
          * NB! When You're dealing with stored function index should start with number 2!
         public void registerArgument(int index, Object value, int type, int inOutType) {
              arguments.put(new Long(index), new CallableStatementArgument(value, type, inOutType));
         private String getSQL() {
              StringBuffer str = new StringBuffer("{ call  ");
              if ( type == CALL_TYPE__FUNCTION )
                   str.append(" ? := ");
              str.append(name).append("( ");
              for ( Iterator i = arguments.values().iterator(); i.hasNext(); ) {
                   i.next();
                   str.append("?");
                   if ( i.hasNext() )
                        str.append(", ");
              str.append(") }");
              return str.toString();
         public void execute() throws SQLException{
              String query = getSQL();
              statement = con.prepareCall(query);
              if ( type == CALL_TYPE__FUNCTION )
                   statement.registerOutParameter(1, resultType);
              for ( Iterator i = arguments.keySet().iterator(); i.hasNext(); ) {
                   Long index = (Long) i.next();
                   CallableStatementArgument argument = (CallableStatementArgument) arguments.get(index);
                   int type = argument.getType();
                   if ( argument.getInOutType() == PARAMETER__OUT )
                        statement.registerOutParameter(index.intValue(), type);
                   else if ( type != OracleTypes.CURSOR )
                        statement.setObject(index.intValue(), argument.getValue(), type);
              log.info("Executing SQL: "+query);
              statement.execute();
         public CallableStatement getStatement() {
              return statement;
         public void close() throws EhlApplicationException {
              try {
                   if (statement != null)
                        statement.close();
                   if (con != null)
                        con.close();
              catch (SQLException e) {
                   EhlSqlExceptionHelper.process(e);
         private class CallableStatementArgument implements Serializable{
              private Object value;
              private int type;
              private int inOutType;
              public CallableStatementArgument(Object value, int type, int inOutType) {
                   this.value = value;
                   this.type = type;
                   this.inOutType = inOutType;
              public int getType() {
                   return type;
              public Object getValue() {
                   return value;
              public int getInOutType() {
                   return inOutType;
    }It was really done in 10-15 mins, so don't be very angry at code quality :)
    Here is the problem.:
                   helper.registerProcedure("pkg_diagnosis.search_diagnosis");
                   helper.registerArgument(1, null, OracleTypes.CURSOR, EhlJdbcCallableStatementHelper.PARAMETER__OUT);
                   helper.registerArgument(2, pattern, OracleTypes.VARCHAR, EhlJdbcCallableStatementHelper.PARAMETER__IN);
                   helper.registerArgument(3, lang, OracleTypes.VARCHAR, EhlJdbcCallableStatementHelper.PARAMETER__IN);
                   helper.registerArgument(4, EhlSqlUtil.convertSetToString(langs, ","), OracleTypes.VARCHAR, EhlJdbcCallableStatementHelper.PARAMETER__IN);
                   helper.registerArgument(5, EhlSqlUtil.convertSetToString(diagnosisClass, ","), OracleTypes.VARCHAR, EhlJdbcCallableStatementHelper.PARAMETER__IN);
                   helper.registerArgument(6, parentId, OracleTypes.NUMBER, EhlJdbcCallableStatementHelper.PARAMETER__IN);
                   helper.execute();
                   ResultSet rs = ((OracleCallableStatement) helper.getStatement()).getCursor(1);
                   procedure definition:
    procedure search_diagnosis (l_res OUT dyna_cur,
                               in_search_string IN VARCHAR2,
                               in_search_lang IN VARCHAR2,
                               in_lang_list IN VARCHAR2,
                               in_diag_class_list IN VARCHAR2,
                               in_parent_id IN NUMBER) Procedure call has inner check that fail because of som strange reason:
    in_search_string has 2 as index, that is correct. but procedure recieves is as number 3 in parameter list (what is in_search_lang). Other parameters are moved to. It seems like a cursor takes 2 places in definition. It's clear that if I put in_search_string as 1 parameter and cursor as 0 I'll get invalid parametr bindong(s) exception. So... any ideas why 2nd parameter is actually 3rd?
    Thanks beforehand.

    hmm...moreover:
    if we change procedure to function and call it in a simple way:
    CallableStatement stmnt = helper.getConnection().prepareCall("begin ? := pkg_diagnosis.search_diagnosis(?,?,?,?,?); end;");
                   stmnt.registerOutParameter(1, OracleTypes.CURSOR);
                   stmnt.setString(2, pattern);
                   stmnt.setString(3, lang);
                   stmnt.setString(4, langs);
                   stmnt.setString(5, diagnosisClass);
                   stmnt.setObject(6, parentId, OracleTypes.NUMBER);
                   stmnt.execute();
                   ResultSet rs = (ResultSet) stmnt.getObject(1);the exception is:
    [BEA][Oracle JDBC Driver][Oracle]ORA-06550: line 1, column 14:
    PLS-00382: expression is of wrong type
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignoredif we return some string or number - it works. but when we want cursor back - it fails.
    cursor is defined like ordinary dynamic cursor:
    TYPE dyna_cur IS REF CURSOR;

Maybe you are looking for

  • Original Garageband Loops missing

    None of the original GB loops appear in the browser; only the jampack loops I downloaded from .Mac are there. I located the loops in the /Library/Application Support/Garageband folder. My GB app is working from the ~/Library/Application Support/Garag

  • Flash Player Security Settings per your D:/ drive...

    Hi, For anyone who read my post earlier in the day, I apologize for the redundancy; this is a new issue for me. I've been working on an e-learning product using Flash Builder; it was developed to be web-based, but the client has changed the requireme

  • Open a Large PTIF in PS?

    I downloaded an image from the NASA LROC Site that is around 10,000 x 68,000 pixels in size. It is HUGE! But I get an error message from Photoshop when attempting to open the file: Photoshop can only decode JPEG encoded images up to 32767 pixels wide

  • Default dml statements.

    Hi Everybody, Season Greetings! I've a form using one base table block (multi-record format), lets say I'm creating a new row, Oracle forms builds a Default Insert statement when I commit the transaction. Same as with Update and Delete commands, my q

  • Can't find AE CC Folder?

    I'll try to explain the whole situation to better explain the situation. I got a colorpack from FilmRiot in which you put the presets in a folder for After Effects. When I originally got this, I had After Effects CS6, I was able to find the support f