How to do  store with dynamic sql to return a cursor

i need to do a store that returns a cursor, but the expression of the cursor are genereted dynamicly. how can i do that?
something like this:
sql_stmt := 'SELECT * FROM ' || INTABLE || ' WHERE '|| inWhereClause;
EXECUTE IMMEDIATE sql_stmt into C1;
where c1 is a ref cursor( OUT variable of procedure)
it is possible or not?
Pedro Cardoso

The syntax is something like
sql_stmt := 'Select * from '|| InTable||' WHERE '|| InWhereClause ;
OPEN C1 for Sql_Stmt ;

Similar Messages

  • How to generate report with dynamic variable number of columns?

    How to generate report with dynamic variable number of columns?
    I need to generate a report with varying column names (state names) as follows:
    SELECT AK, AL, AR,... FROM States ;
    I get these column names from the result of another query.
    In order to clarify my question, Please consider following table:
    CREATE TABLE TIME_PERIODS (
    PERIOD     VARCHAR2 (50) PRIMARY KEY
    CREATE TABLE STATE_INCOME (
         NAME     VARCHAR2 (2),
         PERIOD     VARCHAR2 (50)     REFERENCES TIME_PERIODS (PERIOD) ,
         INCOME     NUMBER (12, 2)
    I like to generate a report as follows:
    AK CA DE FL ...
    PERIOD1 1222.23 2423.20 232.33 345.21
    PERIOD2
    PERIOD3
    Total 433242.23 56744.34 8872.21 2324.23 ...
    The TIME_PERIODS.Period and State.Name could change dynamically.
    So I can't specify the state name in Select query like
    SELECT AK, AL, AR,... FROM
    What is the best way to generate this report?

    SQL> -- test tables and test data:
    SQL> CREATE TABLE states
      2    (state VARCHAR2 (2))
      3  /
    Table created.
    SQL> INSERT INTO states
      2  VALUES ('AK')
      3  /
    1 row created.
    SQL> INSERT INTO states
      2  VALUES ('AL')
      3  /
    1 row created.
    SQL> INSERT INTO states
      2  VALUES ('AR')
      3  /
    1 row created.
    SQL> INSERT INTO states
      2  VALUES ('CA')
      3  /
    1 row created.
    SQL> INSERT INTO states
      2  VALUES ('DE')
      3  /
    1 row created.
    SQL> INSERT INTO states
      2  VALUES ('FL')
      3  /
    1 row created.
    SQL> CREATE TABLE TIME_PERIODS
      2    (PERIOD VARCHAR2 (50) PRIMARY KEY)
      3  /
    Table created.
    SQL> INSERT INTO time_periods
      2  VALUES ('PERIOD1')
      3  /
    1 row created.
    SQL> INSERT INTO time_periods
      2  VALUES ('PERIOD2')
      3  /
    1 row created.
    SQL> INSERT INTO time_periods
      2  VALUES ('PERIOD3')
      3  /
    1 row created.
    SQL> INSERT INTO time_periods
      2  VALUES ('PERIOD4')
      3  /
    1 row created.
    SQL> CREATE TABLE STATE_INCOME
      2    (NAME   VARCHAR2 (2),
      3       PERIOD VARCHAR2 (50) REFERENCES TIME_PERIODS (PERIOD),
      4       INCOME NUMBER (12, 2))
      5  /
    Table created.
    SQL> INSERT INTO state_income
      2  VALUES ('AK', 'PERIOD1', 1222.23)
      3  /
    1 row created.
    SQL> INSERT INTO state_income
      2  VALUES ('CA', 'PERIOD1', 2423.20)
      3  /
    1 row created.
    SQL> INSERT INTO state_income
      2  VALUES ('DE', 'PERIOD1', 232.33)
      3  /
    1 row created.
    SQL> INSERT INTO state_income
      2  VALUES ('FL', 'PERIOD1', 345.21)
      3  /
    1 row created.
    SQL> -- the basic query:
    SQL> SELECT   SUBSTR (time_periods.period, 1, 10) period,
      2             SUM (DECODE (name, 'AK', income)) "AK",
      3             SUM (DECODE (name, 'CA', income)) "CA",
      4             SUM (DECODE (name, 'DE', income)) "DE",
      5             SUM (DECODE (name, 'FL', income)) "FL"
      6  FROM     state_income, time_periods
      7  WHERE    time_periods.period = state_income.period (+)
      8  AND      time_periods.period IN ('PERIOD1','PERIOD2','PERIOD3')
      9  GROUP BY ROLLUP (time_periods.period)
    10  /
    PERIOD             AK         CA         DE         FL                                             
    PERIOD1       1222.23     2423.2     232.33     345.21                                             
    PERIOD2                                                                                            
    PERIOD3                                                                                            
                  1222.23     2423.2     232.33     345.21                                             
    SQL> -- package that dynamically executes the query
    SQL> -- given variable numbers and values
    SQL> -- of states and periods:
    SQL> CREATE OR REPLACE PACKAGE package_name
      2  AS
      3    TYPE cursor_type IS REF CURSOR;
      4    PROCEDURE procedure_name
      5        (p_periods   IN     VARCHAR2,
      6         p_states    IN     VARCHAR2,
      7         cursor_name IN OUT cursor_type);
      8  END package_name;
      9  /
    Package created.
    SQL> CREATE OR REPLACE PACKAGE BODY package_name
      2  AS
      3    PROCEDURE procedure_name
      4        (p_periods   IN     VARCHAR2,
      5         p_states    IN     VARCHAR2,
      6         cursor_name IN OUT cursor_type)
      7    IS
      8        v_periods          VARCHAR2 (1000);
      9        v_sql               VARCHAR2 (4000);
    10        v_states          VARCHAR2 (1000) := p_states;
    11    BEGIN
    12        v_periods := REPLACE (p_periods, ',', ''',''');
    13        v_sql := 'SELECT SUBSTR(time_periods.period,1,10) period';
    14        WHILE LENGTH (v_states) > 1
    15        LOOP
    16          v_sql := v_sql
    17          || ',SUM(DECODE(name,'''
    18          || SUBSTR (v_states,1,2) || ''',income)) "' || SUBSTR (v_states,1,2)
    19          || '"';
    20          v_states := LTRIM (SUBSTR (v_states, 3), ',');
    21        END LOOP;
    22        v_sql := v_sql
    23        || 'FROM     state_income, time_periods
    24            WHERE    time_periods.period = state_income.period (+)
    25            AND      time_periods.period IN (''' || v_periods || ''')
    26            GROUP BY ROLLUP (time_periods.period)';
    27        OPEN cursor_name FOR v_sql;
    28    END procedure_name;
    29  END package_name;
    30  /
    Package body created.
    SQL> -- sample executions from SQL:
    SQL> VARIABLE g_ref REFCURSOR
    SQL> EXEC package_name.procedure_name ('PERIOD1,PERIOD2,PERIOD3','AK,CA,DE,FL', :g_ref)
    PL/SQL procedure successfully completed.
    SQL> PRINT g_ref
    PERIOD             AK         CA         DE         FL                                             
    PERIOD1       1222.23     2423.2     232.33     345.21                                             
    PERIOD2                                                                                            
    PERIOD3                                                                                            
                  1222.23     2423.2     232.33     345.21                                             
    SQL> EXEC package_name.procedure_name ('PERIOD1,PERIOD2','AK,AL,AR', :g_ref)
    PL/SQL procedure successfully completed.
    SQL> PRINT g_ref
    PERIOD             AK         AL         AR                                                        
    PERIOD1       1222.23                                                                              
    PERIOD2                                                                                            
                  1222.23                                                                              
    SQL> -- sample execution from PL/SQL block
    SQL> -- using parameters derived from processing
    SQL> -- cursors containing results of other queries:
    SQL> DECLARE
      2    CURSOR c_period
      3    IS
      4    SELECT period
      5    FROM   time_periods;
      6    v_periods   VARCHAR2 (1000);
      7    v_delimiter VARCHAR2 (1) := NULL;
      8    CURSOR c_states
      9    IS
    10    SELECT state
    11    FROM   states;
    12    v_states    VARCHAR2 (1000);
    13  BEGIN
    14    FOR r_period IN c_period
    15    LOOP
    16        v_periods := v_periods || v_delimiter || r_period.period;
    17        v_delimiter := ',';
    18    END LOOP;
    19    v_delimiter := NULL;
    20    FOR r_states IN c_states
    21    LOOP
    22        v_states := v_states || v_delimiter || r_states.state;
    23        v_delimiter := ',';
    24    END LOOP;
    25    package_name.procedure_name (v_periods, v_states, :g_ref);
    26  END;
    27  /
    PL/SQL procedure successfully completed.
    SQL> PRINT g_ref
    PERIOD             AK         AL         AR         CA         DE         FL                       
    PERIOD1       1222.23                           2423.2     232.33     345.21                       
    PERIOD2                                                                                            
    PERIOD3                                                                                            
    PERIOD4                                                                                            
                  1222.23                           2423.2     232.33     345.21                       

  • Writing to a temp table in a stored procedure with dynamic sql

    Hi
    I am writing into a temp table with dynamic sql:
    select coloum_name into #temp_table from
    +
    @DestinationDBName+'.information_schema.tables
    and then I am trying to use #temp_table in the procedure:
    select coloum_name into #anotherTable from #temp_table
    but I am getting an error that #temp_table is not recognized.
    Can a temp table not be used in dynamic sql ?
    How can I overcome this problem ?

    Temp Table Can used easily in Dynamic Query in SQL Server and here is small Exmaple you can check it and do like it 
    CREATE PROC test
    AS
    BEGIN
    CREATE TABLE #T1 
    (ID  int , NAME Nvarchar(50))
    CREATE TABLE #T2 
    (ID  int , NAME Nvarchar(50))
    DECLARE @SQL NVARCHAR(MAX)='Insert into #T1 
    SELECT database_id , Name FROM Sys.Databases
    Insert into #T2 Select ID , Name from  #T1 '
    EXEC SP_ExecuteSQL @SQL
    SELECT * FROM #T2
    DROP TABLE #T1
    DROP TABLE #T2
    END
    Exec Test
    If you found My reply is helpful for you please vote me 
    thanks
    Mustafa EL-Masry
    Principle Database Administrator & DB Analyst
    SQL Server MCTS-MCITP
    M| +966 54 399 0968
    MostafaElmasry.Wordpress.Com

  • Backup DB with dynamic sql - want to substitute in dbname and disk file path

    Re: Backup DB with dynamic sql - want to substitute in dbname and disk file path
    Hope I can explain this. Below is a small snippet of code. I want to set @SQLTemplate_TSQL once at the top of the script and then execute the SET @SQLCommand and sp_executesql in a loop that reads a list of databases. It all works, except for the
    BACKUP DATABASE. Right now it evaluates when the SET @SQLTemplate_TSQL is evaluated. I want it to evaluate when it is executed. I want the DB_NAME() of the USE @dbname.
    -- change @dbname and @dbbackuppath
    DECLARE @SQLCommand NVARCHAR(MAX)
    DECLARE @SQLTemplate_TSQL NVARCHAR(MAX)
    DECLARE @dbname varchar(128) = 'Bank04'
    -- one time setting of @SQLTemplate_TSQL
    set @SQLTemplate_TSQL =
    DECLARE @dbbackuppath varchar(128) = ''''d:\backups''''
    IF RIGHT(@dbbackuppath, 1) <> ''''\''''
    SET @dbbackuppath = @dbbackuppath + ''''\''''
    SET @dbbackuppath = @dbbackuppath + DB_Name() + ''''.bak''''
    PRINT @dbbackuppath
    BACKUP DATABASE ' + DB_NAME() + ' to DISK=''' + QUOTENAME(@dbbackuppath, CHAR(39)) + '''
    -- Execute this several times over different databases
    SET @SQLCommand = '
    USE ' + QUOTENAME(@dbname) + ';
    EXEC(''' + @SQLTemplate_TSQL + ''') '
    PRINT @SQLCommand
    EXECUTE sp_executesql @SQLCommand

    Here is a stripped down version of my code. Someone writes a script. I then take the script and seperate it by GO statement block. Each GO block gets its own row into the
    #SQLTemplate_TSQL. I then replace single quote with 4 quotes and run it. Then I run against my list of databases. I am unable to get the BACKUP DATA base to work with this model.
    Run scripts against multiple databases.sql
    Do a FIND on "CHANGE THIS" to see the databases returned from the SELECT statement
    DECLARE @DatabaseName varchar(128)
    DECLARE @SQLCommand NVARCHAR(MAX)
    DECLARE @SQLTemplate_Seq INT
    DECLARE @SQLTemplate_OperationDesc NVARCHAR(128)
    DECLARE @SQLTemplate_TSQL NVARCHAR(MAX)
    DECLARE @SQLTemplate_Diagnostics INT
    DECLARE @Note VARCHAR(500)
    IF OBJECT_ID('tempdb..#SQLTemplate_TSQL') IS NOT NULL
    DROP TABLE #SQLTemplate_TSQL
    CREATE TABLE [dbo].[#SQLTemplate_TSQL](
    [SQLTemplate_RecID] [int] Identity,
    [SQLTemplate_ID] [int] NOT NULL,
    [SQLTemplate_Seq] [int] NOT NULL,
    [SQLTemplate_OperationDesc] [varchar](128) NOT NULL,
    [SQLTemplate_TSQL] [varchar](max) NOT NULL,
    [SQLTemplate_Diagnostics] [int] NOT NULL,
    [SQLTemplate_Enabled] [int] NOT NULL)
    DELETE FROM #SQLTemplate_TSQL WHERE SQLTemplate_Seq = 65
    DECLARE @SeqID INT
    SELECT @SeqID = MAX(SQLTemplate_ID) FROM #SQLTemplate_TSQL
    SET @SeqID = ISNULL(@SeqID,0)
    SET @SeqID = @SeqID + 1
    INSERT INTO #SQLTemplate_TSQL VALUES(@SeqID ,65,@SeqID,'
    SELECT * FROM ifs_config
    ',1,1)
    SET @SeqID = @SeqID + 1
    INSERT INTO #SQLTemplate_TSQL VALUES(@SeqID ,65,@SeqID,'
    DECLARE @HistoryODS INT
    SET @HistoryODS = 1
    SELECT * FROM ifs_tablelist WHERE HistoryODS = @HistoryODS and Tablename like ''''%HIST%''''
    ',1,1)
    -- Setup Cursor to Loop through each of the Prior Period databases
    DECLARE db_cursor CURSOR FOR
    SELECT [Database Name] --<<<<<<<< CHANGE THIS SELECT statement to select DBs >>>>>>
    FROM v_ifs_PPODSDBInfo_Curr
    WHERE [Database Frequency] <> 'CURRENT'
    ORDER BY [Database Frequency], [Database Number]
    OPEN db_cursor
    FETCH NEXT FROM db_cursor INTO @DatabaseName
    -- Loop through each of the databases
    WHILE @@FETCH_STATUS = 0
    BEGIN
    -- Setup Cursor to Loop through each of the SQL Statements
    DECLARE #SQLTemplate_TSQL_cursor CURSOR FOR
    SELECT [SQLTemplate_TSQL], [SQLTemplate_OperationDesc], [SQLTemplate_Seq], [SQLTemplate_Diagnostics]
    FROM #SQLTemplate_TSQL
    WHERE [SQLTemplate_Enabled] = 1 AND SQLTemplate_Seq = 65
    ORDER BY SQLTemplate_ID
    OPEN #SQLTemplate_TSQL_cursor
    FETCH NEXT FROM #SQLTemplate_TSQL_cursor INTO @SQLTemplate_TSQL, @SQLTemplate_OperationDesc, @SQLTemplate_Seq, @SQLTemplate_Diagnostics
    -- Loop through each of the SQL statements
    WHILE @@FETCH_STATUS = 0
    BEGIN
    SET @SQLCommand = '
    USE ' + QUOTENAME(@Databasename) + ';
    EXEC(''' + @SQLTemplate_TSQL + ''') '
    EXECUTE sp_executesql @SQLCommand
    FETCH NEXT FROM #SQLTemplate_TSQL_cursor INTO @SQLTemplate_TSQL, @SQLTemplate_OperationDesc, @SQLTemplate_Seq, @SQLTemplate_Diagnostics
    END
    CLOSE #SQLTemplate_TSQL_cursor
    DEALLOCATE #SQLTemplate_TSQL_cursor
    FETCH NEXT FROM db_cursor INTO @DatabaseName
    END
    CLOSE db_cursor
    DEALLOCATE db_cursor

  • How to create CATALOG with MS SQL Server?

    Connection class has getCatalog(strCatalog) method. In order to use it, we must create CATALOG in Database?
    How to create CATALOG with MS SQL Server?
    Help me, please!!!

    You do not create these for any database, this is part of the Connection metadata.
    The Catalog is the third level of table-like database object qualification as in "Catalog.Schema.Table". For SQLServer the qualification scheme is "Database.Owner.Table" and I would be surprised if they reported anything for the current connections getCatalog() method call.
    What many people do is avoid table qualification altogether by setting the connection's context in a database proprietary manner and then keeping the SQL as clean as possible. For many ODBC and JDBC drivers this can be set in the configuration. For MS SQLServer you can also execute a "USE dbname" statement on the connection to avoid table qualification.

  • DB2 problems with Dynamic SQL

    Does anyone out there use dynamic SQL with DB2? If so, are the sql statements causing a PreparedStatement to be executed on DB2. I posted this question similarly before, but never resolved it, and it is killing me. I have to resolve this ASAP!
    Here is the problem: My DB2 Admin says that EVERY TIME I access the database, my Java app is causing the database to create a PreparedStatement. However, I'm using Statement objects exclusively, with dynamic SQL. He says that DB2 needs an "access path" for the client, and that it converts the Statement to a PreparedStatement, as this is the only way to get this "access path". He says the only solution is either stored procedures or SQLJ, which will do the binding in advance, and increase performance tremendously. However, I am STRONGLY opposed to using SQLJ, and if we do stored procedures, we'd have to write one for every possible SQL statment! I KNOW there is a better solution.
    Is anyone out there having these problems with JDBC and DB2? Surely someone out there uses DB2 and JDBC and either has these problems or can confirm that something is incorrectly configured on the database side.
    Any help would be great. Thanks, Will

    Now I'm wondering if maybe the PreparedStatements are ONLY being called on the database when I call getConnection(), and not when I call executeQuery() or executeUpdate() from the Statement object. I just can't see why the database would have to make an access path for every SQL statement executed, but I could see it creating an access path for every connection requested. Any thoughts on that theory?

  • Help with dynamic SQL

    Hello,
    I have the following function that works ok:
    CREATE OR REPLACE FUNCTION Get_Partition_Name (sTable VARCHAR2, iImportIndex INTEGER)
    RETURN VARCHAR2 IS
    cursor c is select A.partition_name from (select table_name, partition_name,
    extractvalue (
    dbms_xmlgen.
    getxmltype (
    'select high_value from all_tab_partitions where table_name='''
    || table_name
    || ''' and table_owner = '''
    || table_owner
    || ''' and partition_name = '''
    || partition_name
    || ''''),
    '//text()') import_value from all_tab_partitions) A where table_name = sTable and A.import_value = iImportIndex;
    sPartitionName VARCHAR(20);
    err_num NUMBER;
    BEGIN
    open c;
    fetch c into sPartitionName;
    IF c%ISOPEN THEN
    CLOSE c;
    END IF;
    RETURN sPartitionName;
    EXCEPTION
    WHEN OTHERS THEN
    err_num := SQLCODE;
    --save error in log table
    LOG.SAVELINE(SQLCODE, SQLERRM);
    END Get_Partition_Name;
    I am trying to replace the cursor statement with dynamic SQL, something like (see below) but it doesn't work any more; I think I am missing some quotes.
    CREATE OR REPLACE FUNCTION Get_Partition_Name (sTable VARCHAR2, iImportIndex INTEGER)
    RETURN VARCHAR2 IS
    TYPE t1 IS REF CURSOR;
    c t1;
    sSql VARCHAR2(500);
    sPartitionName VARCHAR(20);
    err_num NUMBER;
    BEGIN
    sSql := 'select A.partition_name from (select table_name, partition_name,
    extractvalue (
    dbms_xmlgen.
    getxmltype (
    ''select high_value from all_tab_partitions where table_name=''''
    || table_name
    || '''' and table_owner = ''''
    || table_owner
    || '''' and partition_name = ''''
    || partition_name
    || ''''''),
    ''//text()'') import_value from all_tab_partitions) A where table_name = :a and A.import_value = :b';
    OPEN c FOR sSql USING sTable, iImportIndex;
    fetch c into sPartitionName;
    IF c%ISOPEN THEN
    CLOSE c;
    END IF;
    RETURN sPartitionName;
    EXCEPTION
    WHEN OTHERS THEN
    err_num := SQLCODE;
    --save error in log table
    LOG.SAVELINE(SQLCODE, SQLERRM);
    END Get_Partition_Name;
    Please advise,
    Regards,
    M.R.

    Assuming the requirement is to find the partition in the supplied table with the supplied high value and the issue is that dba/all_tab_partitions.high_value is a long, one alternative along the same lines as you've done already is as follows. (I've just used a cursor rather than a function for simplicity of demo).
    SQL> var r refcursor
    SQL> set autoprint on
    SQL> declare
      2   ctx dbms_xmlgen.ctxhandle;
      3   v_table_name VARCHAR2(40) := 'LOGMNR_USER$';
      4   v_value      NUMBER       := 100;
      5  begin
      6   ctx := DBMS_XMLGEN.NEWCONTEXT
      7          ('select table_name
      8            ,      partition_name
      9            ,      high_value  hi_val
    10            from   dba_tab_partitions
    11            where  table_name     = :table_name');
    12   dbms_xmlgen.setbindvalue(ctx,'TABLE_NAME',v_table_name);
    13   open:r for
    14   with x as
    15   (select xmltype(dbms_xmlgen.getxml(ctx)) myxml
    16    from   dual)
    17   select extractvalue(x.object_value,'/ROW/TABLE_NAME') table_name
    18   ,      extractvalue(x.object_value,'/ROW/PARTITION_NAME') partition_name
    19   ,      extractvalue(x.object_value,'/ROW/HI_VAL') hi_val
    20   from   x
    21   ,      TABLE(XMLSEQUENCE(EXTRACT(x.myxml,'/ROWSET/ROW'))) x
    22   where  extractvalue(x.object_value,'/ROW/HI_VAL') = v_value;
    23  end;
    24  /
    PL/SQL procedure successfully completed.
    TABLE_NAME
    PARTITION_NAME
    HI_VAL
    LOGMNR_USER$
    P_LESSTHAN100
    100
    SQL> I'm sure there are other ways as well. Especially with XML functionality, there's normally many ways to skin a cat.

  • How create data store with PermSize 512MB on WIN32?

    Hi!
    How create data store with PermSize > 512MB on WIN32? If I set PermSize > 512MB on WIN32, then data store becomes invalid.

    Thanks for the details. As I mentioned, due to issues with the way Windows manages memory and address space it is generally not possible to create a datastore larger than around 700 Mb on WIN32. Sometimes you may be lucky and get close to 1 GB but usually not. The issue is as follows; on Windows, a TimesTen datastore is a shared mapping created from memory backed by the paging file. This shared mapping must be mapped into the process address space as a contiguous range of addresses. So, if you have a 1 GB datastore then your process needs to have a contiguous 1 GB range of addresses free in order to be able to connect to (map) the datastore. Unfortunately the default behaviour of Windows is to map DLLs into a process address space all over the place and any process that uses any significant number of DLLs is very unlikely to have a contiguous free address range larger than 500-700 Mb.
    This problem does not exist with other O/S such as Unix or Linux nor does it exist with 64-bit Windows. So, if you need to use a cache or datastore larger than around 700 Mb you need to use either 64-it Windows or another O/S. Note that even on 32-bit Linux/Unix TimesTen datastores are limited to a maximum size of 2 GB. If you need more than 2 GB you need to use a 64-bit O/S.
    Chris

  • Alternative to native, dynamic sql to return a ref cursor to a client

    I'm on Oracle 8.0.4, and would like to pass a string of values like '1,2,7,100,104' that are the primary key for a table. Then use something like:
    procedure foo( MyCur RefCurType, vKey varchar2)
    begin
    open MyCur for
    'select names from SomeTable' &#0124; &#0124;
    ' where ID in (' &#0124; &#0124; vKey &#0124; &#0124; ')'
    end;
    This would return a recordset to (in this case) a Crystal Reports report.
    However, native dynamic SQL ain't available until 8.1.0. So can anyone think of a clever way to accomplish this, with a way to return a cursor? I can't figure out how to do this with DBMS_SQL, because open_cursor is just returning a handle, not a referene to a cursor that can be passed to a remote client.
    Thanks in advance.

    I'm on Oracle 8.0.4, and would like to pass a string of values like '1,2,7,100,104' that are the primary key for a table. Then use something like:
    procedure foo( MyCur RefCurType, vKey varchar2)
    begin
    open MyCur for
    'select names from SomeTable' &#0124; &#0124;
    ' where ID in (' &#0124; &#0124; vKey &#0124; &#0124; ')'
    end;
    This would return a recordset to (in this case) a Crystal Reports report.
    However, native dynamic SQL ain't available until 8.1.0. So can anyone think of a clever way to accomplish this, with a way to return a cursor? I can't figure out how to do this with DBMS_SQL, because open_cursor is just returning a handle, not a referene to a cursor that can be passed to a remote client.
    Thanks in advance.

  • How to create a function with dynamic sql or any better way to achieve this?

            Hello,
            I have created below SQL query which works fine however when scalar function created ,it
            throws an error "Only functions and extended stored procedures can be executed from within a
            function.". In below code First cursor reads all client database names and second cursor
            reads client locations.
                      DECLARE @clientLocation nvarchar(100),@locationClientPath nvarchar(Max);
                      DECLARE @ItemID int;
                      SET @locationClientPath = char(0);
                      SET @ItemID = 67480;
       --building dynamic sql to replace database name at runtime
             DECLARE @strSQL nvarchar(Max);
             DECLARE @DatabaseName nvarchar(100);
             DECLARE @localClientPath nvarchar(MAX) ;
                      Declare databaselist_cursor Cursor for select [DBName] from [DataBase].[dbo].
                      [tblOrganization] 
                      OPEN databaselist_cursor
                      FETCH NEXT FROM databaselist_cursor INTO @DatabaseName
                      WHILE @@FETCH_STATUS = 0
                      BEGIN       
       PRINT 'Processing DATABASE: ' + @DatabaseName;
        SET @strSQL = 'DECLARE organizationlist_cursor CURSOR
        FOR SELECT '+ @DatabaseName +'.[dbo].[usGetLocationPathByRID]
                                   ([LocationRID]) 
        FROM '+ @DatabaseName +'.[dbo].[tblItemLocationDetailOrg] where
                                   ItemId = '+ cast(@ItemID as nvarchar(20))  ;
         EXEC sp_executesql @strSQL;
        -- Open the cursor
        OPEN organizationlist_cursor
        SET @localClientPath = '';
        -- go through each Location path and return the 
         FETCH NEXT FROM organizationlist_cursor into @clientLocation
         WHILE @@FETCH_STATUS = 0
          BEGIN
           SELECT @localClientPath =  @clientLocation; 
           SELECT @locationClientPath =
    @locationClientPath + @clientLocation + ','
           FETCH NEXT FROM organizationlist_cursor INTO
    @clientLocation
          END
           PRINT 'current databse client location'+  @localClientPath;
         -- Close the Cursor
         CLOSE organizationlist_cursor;
         DEALLOCATE organizationlist_cursor;
         FETCH NEXT FROM databaselist_cursor INTO @DatabaseName
                    END
                    CLOSE databaselist_cursor;
                    DEALLOCATE databaselist_cursor;
                    -- Trim the last comma from the string
                   SELECT @locationClientPath = SUBSTRING(@locationClientPath,1,LEN(@locationClientPath)-  1);
                     PRINT @locationClientPath;
            I would like to create above query in function so that return value would be used in 
            another query select statement and I am using SQL 2005.
            I would like to know if there is a way to make this work as a function or any better way
            to  achieve this?
            Thanks,

    This very simple: We cannot use dynamic SQL from used-defined functions written in T-SQL. This is because you are not permitted do anything in a UDF that could change the database state (as the UDF may be invoked as part of a query). Since you can
    do anything from dynamic SQL, including updates, it is obvious why dynamic SQL is not permitted as per the microsoft..
    In SQL 2005 and later, we could implement your function as a CLR function. Recall that all data access from the CLR is dynamic SQL. (here you are safe-guarded, so that if you perform an update operation from your function, you will get caught.) A word of warning
    though: data access from scalar UDFs can often give performance problems and its not recommended too..
    Raju Rasagounder Sr MSSQL DBA
          Hi Raju,
           Can you help me writing CLR for my above function? I am newbie to SQL CLR programming.
           Thanks in advance!
           Satya
              

  • Erratic Report Region Behavior with Dynamic SQL Queries

    I'm running HTMLDB v 1.5.1.00.12 and I've noticed some odd behavior with report regions using dynamic SQL queries. Every so often, our testers will run a page containing a dynamic sql report region and get the following error, (despite the fact the query was working only moments ago and no other developer has touched it):
    ORA-06502: PL/SQL: numeric or value error: character string buffer too small
    or sometimes
    failed to parse SQL query:ORA-01403: no data found
    The only solution I've found so far is to:
    1) Make a copy of the failed report region.
    2) Disable or delete the original failed report region.
    The new copy of the report region runs without issue.
    My search of the forums turned up the following two threads, but neither provided me with a clear explanation of the cause, and how to avoid it:
    ORA-06502:PL/SQL: numeric or value error: character string buffer too small
    Re: Import Export Error (ORA-06502)
    The columns being returned are below the 4000 character limit, and the rows being returned are far less than 32k in size.
    Could this have anything to do with the way HTMLDB is internally storing the PL/SQL used to generate the dynamic SQL Query? Is there any known issue related to this with that version of HTMLDB?
    This problem occurs without any discernable pattern or consistency, making it hard to determine where I should focus my efforts in tracking down the cause.

    Hi all,
    My report seems to be behaving correctly once i set it to "Use Generic Column Names (parse query at runtime only)" :)
    Cheers,
    Joel

  • Using bind variables (in & out) with dynamic sql

    I got a table that holds pl/sql code snippets to do validations on a set of data. what the code basically does is receiving a ID and returning a number of errors found.
    To execute the code I use dynamic sql with two bind variables.
    When the codes consists of a simpel query, it works like a charm, for example with this code:
    BEGIN
       SELECT COUNT (1)
       INTO :1
       FROM articles atl
       WHERE ATL.CSE_ID = :2 AND cgp_id IS NULL;
    END;however when I get to some more complex validations that need to do calculations or execute multiple queries, I'm running into trouble.
    I've boiled the problem down into this:
    DECLARE
       counter   NUMBER;
       my_id     NUMBER := 61;
    BEGIN
       EXECUTE IMMEDIATE ('
          declare
             some_var number;
          begin
          select 1 into some_var from dual
          where :2 = 61;
          :1 := :2;
          end;
          USING OUT counter, IN my_id;
       DBMS_OUTPUT.put_line (counter || '-' || my_id);
    END;this code doesn't really make any sense, but it's just to show you what the problem is. When I execute this code, I get the error
    ORA-6537 OUT bind variable bound to an IN position
    The error doesn't seem to make sense, :2 is the only IN bind variable, and it's only used in a where clause.
    As soon as I remove that where clause , the code will work again (giving me 61-61, in case you liked to know).
    Any idea whats going wrong? Am I just using the bind variables in a way you're not supposed to use them?
    I'm using Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit

    Correction. With execute immediate binding is by position, but binds do not need to be repeated. So my statement above is incorrect..
    You need to bind it once only - but bind by position. And the bind must match how the bind variable is used.
    If the bind variable never assigns a value in the code, bind as IN.
    If the bind variable assigns a value in the code, bind as OUT.
    If the bind variable assigns a value and is used a variable in any other statement in the code, bind as IN OUT.
    E.g.
    SQL> create or replace procedure FooProc is
      2          cnt     number;
      3          id      number := 61;
      4  begin
      5          execute immediate
      6  'declare
      7          n       number;
      8  begin
      9          select
    10                  1 into n
    11          from dual
    12          where :var1 = 61;       --// var1 is used as IN
    13 
    14          :var2 := n * :var1;     --// var2 is used as OUT and var1 as IN
    15          :var2 := -1 * :var2;    --// var2 is used as OUT and IN
    16  end;
    17  '
    18          using
    19                  in out id, in out cnt;  --// must reflect usage above
    20 
    21          DBMS_OUTPUT.put_line ( 'cnt='||cnt || ' id=' || id);
    22  end;
    23  /
    Procedure created.
    SQL>
    SQL> exec FooProc
    cnt=-61 id=61
    PL/SQL procedure successfully completed.
    SQL>

  • Flash chart with dynamic sql query does not display

    Hi,
    In my schema SIVOA I have a lot of tables declared like this :
      CREATE TABLE "SIVOA"."EVV_xxxx"
       (     "CLEF_VAR" NUMBER(4,0),
         "DATE1" DATE,
         "VALEUR" NUMBER(16,8) Only the last part of the name changes "xxxx". For example E009, E019, etc....
    I am making a chart page with report and want the user to select a name of a table and I will display using dynamic sql query, the table report and chart.
    P184_ENAME is a select list returning the last part of the name of the table, fro example 'E009', 'E019', etc.
    P8_CLEF_VAR is an item containing a value. This value is a key retrieved like this :SELECT CLEF_VAR
    FROM SIVOA.SITE_ECHELLE
    WHERE SITE = :P184_ENAMEI built a classic report using a sql dynamic function :DECLARE
    x VARCHAR2 (4000);
    BEGIN
    x := 'SELECT NULL, DATE1, VALEUR FROM SIVOA.EVV_'
    || UPPER(:p184_ename)
    || ' WHERE CLEF_VAR = :p8_clef_var' ;
    RETURN (x);
    END;:p8_clef_var is an itme containing the value '4544'.
    This works perfectly fine !
    When I use this sql fucytion into a flash chart it does not work. I get this message "No data found".
    I do not understand why a the report get a result and not the chart !
    But if i hard-code the number of the CLEF_VAR instead of fetching it from :p8_clef_var I get a nice chart ! Go figure !DECLARE
    x VARCHAR2 (4000);
    BEGIN
    x := 'SELECT NULL, DATE1, VALEUR FROM SIVOA.EVV_'
    || UPPER(:p184_ename)
    || ' WHERE CLEF_VAR = 4544 ' ;
    RETURN (x);
    I cannot stay with the key (CLEF_VAR) hard-coded unformtunately !
    My question is how to get the chart displaying properly ??
    Thank you for your kind answers.
    Christian                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Alex,
    Using your request, with the classic report I get results (data), but I get the same message with the Flash chart : "No data found" ! I don't know how to investigate this. i tried many things but nothing works.
    Christian
    PS I tried this :
    DECLARE
       X   VARCHAR2 (4000);
    BEGIN
    x := 'SELECT NULL, DATE1, ROUND(VALEUR,2) FROM SIVOA.EVV_'
          || UPPER (:p184_ename) ||
          ' WHERE CLEF_VAR = '
          || :p8_clef_var ||
          ' AND DATE1 BETWEEN TO_DATE ('''
    ||:P8_DATE_DEBUT||''', ''DD/MM/YYYY HH24:MI'') AND TO_DATE ('''
    ||:P8_DATE_FIN||''', ''DD/MM/YYYY HH24:MI'')'
    RETURN (X);
    END; But it does not work either. I could find that the SLQ syntax generated is good becaus I put it into an item which display the return done by the pls/sql.
    What is sttange also with the classic report is that if I do click on next or previous to see another rows, I get the message "No data found". If I try to export the report I get an excel file with "No data fouid".
    Does anybody already tried my "need" here ? i find strange thant I should not be the firs one trying to get a report an tables which name would be "dynamic".
    Tahnk you.
    Edited by: Christian from France on Feb 13, 2009 3:05 AM

  • How to obtain IR report dynamic SQL in Apex 4.0

    Hello,
    I have 2 regions on the same page
    Interactive Report –
    Chart (Flash Chart) – This is a sub region of the above
    Now the requirement is when user applies a filter to the interactive report I would like to apply the same filter criteria to the flash chart so that data representation in flash chart matches with the IR report content. I am fairly new to the Apex, apologies if  used any apex terminology in correctly
    Appreciate if you  can point me in the right direction
    Thank you
    -Raj

    Hello , I did some research how to achieve this , one way is to get the IR report dynamic sql using APEX_IR.GET_REPORT package and apply the same sql for the chart  so that the chart representation will match with the IR report data, But the challenge is as i am using the APEX 4.0.0.00.46 version, the APEX_IR package is not available in that version , Any other way we can achieve this  in Apex 4.0??
    Thanks
    -raj

  • Query with Dynamic SQL

    Hello,
    I would like to create a Dynamic SQL in which change is the name of the table according to the outcome of the first SQL. This is possible?
    'WITH TABLE_X AS(SELECT LEVEL LVL FROM DUAL CONNECT BY LEVEL <= 12)' ||
    'SELECT A.COL1, A.COL2, B.COL1, B.COL7'                              ||
    '  FROM TABLE_A' || TABLE_X.LVL || ' A'                              ||
    '     , TABLE_B' || TABLE_X.LVL || ' B'                              ||
    ' WHERE A.COL1 = B.COL1 AND ...    'tables in database
    TABLE_A1
    TABLE_A2
    TABLE_A12
    TABLE_B1
    TABLE_B2
    TABLE_B12let me know how I can do this
    Regards

    Hi,
    Sorry, I don't see what you're trying to do.
    "Dynamic SQL" is really a mis-nomer. The number of tables and columns in a query, and their names, must be spelled out when the statement is compiled. There is nothing dynamic about it.
    In dynamic SQL, a PL/SQL procedure or another query writes all or part of query just milliseconds before it is compiled, typically using data taken from tables or supplied by a user right then.
    For example, consider this static query:
    SELECT     a.col1, a.col2, b.col1, b.col7
    FROM     table_1     a
    ,     table_2 b
    WHERE     a.col1 = b.col1;Now, say the 1 in "table_1" and the 2 in "table_2" are variables, x and y, that you will want to look up from another table every time you run this query. You can make it dynamic like this:
    sql_txt := 'SELECT  a.col1, a.col2, b.col1, b.col7 '
         || 'FROM    table_' || TO_CHAR (x) || ' a '
         || ',       table_' || TO_CHAR (y) || ' b '
         || 'WHERE   a.col_1 = b.col1';Now let's make it really interesting. Say that instead of 2 tables, and 1 join condition, you''ll have n tables and n-1 join conditions, where n has to be computed at (actually a split second before) run-time. That is, if n=4, you might need to construct a static query with 4 tables and 3 join conditions, like this:
    SELECT     a.col1, a.col2, b.col1, b.col7
    FROM     table_1     a
    ,     table_2 b
    ,     table_12 c
    ,     table_2 d
    WHERE     a.col1 = b.col1
    AND     a.col1 = c.col1
    AND     a.col1 = d.col1;You can do that using dynamic SQL, too.
    Post an example of the static query you need to build, and describe what parts of it are dynamic, and how you get the values for those parts, and someone will help you write the dynamic SQL.

Maybe you are looking for

  • HP 320-1030 WINDOWS 7 TOUCHSCREE​N SOFTWARE AND WINDOWS 8 UPGRADE

    Just purchased an hp 320-1030 touchscreen with windows 7 operating system. The advertisement was that you could upgrade to windows 8 for $15 and HP would refund the $15.00 When you read the upgrade information it states that HP Touchsmart application

  • Download a file from the web

    Helo, I have to download a file from the web and copy it to the file system (ex: download from http://172.26.20.22/test.csv to \\server01\teste.csv). I must do this using only pl/sql and java sources, I have to do this calling a procedure from pl/sql

  • Automatically output report to excel from a batch job

    We have business users who require that a standard report be run daily as a batch job and output to a printer, which is using a large pile of paper every day.  I have challenged the rationale for this without success, and am trying to find a way to c

  • Why can't I get a book that I pre ordered already

    I pre ordered a book an now that it is out I can't get it it's saying that I have to buy the book all over again

  • Oracle Portal Load Balancing question

    Our customer wishes to have multiple Oracle Application Servers running Oracle Portal, with load balancing. They would like to have Web Cache collocated with one of these Portal servers, operating as a load balancer for the Portal servers (including