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.

Similar Messages

  • Running a SQL Stored Procedure from Power Query with Dynamic Parameters

    Hi,
    I want to execute a stored procedure from Power Query with dynamic parameters.
    In normal process, query will look like below in Power Query. Here the value 'Dileep' is passed as a parameter value to SP.
        Source = Sql.Database("ABC-PC", "SAMPLEDB", [Query="EXEC DBO.spGetData 'Dileep'"]
    Now I want to pass the value dynamically taking from excel sheet. I can get the required excel cell value in a variable but unable to pass it to query.
        Name_Parameter = Excel.CurrentWorkbook(){[Name="Table3"]}[Content],
        Name_Value = Name_Parameter{0}[Value],
    I have tried like below but it is not working.
    Source = Sql.Database("ABC-PC", "SAMPLEDB", [Query="EXEC DBO.spGetData Name_Value"]
    Can anyone please help me with this issue.
    Thanks
    Dileep

    Hi,
    I got it. Below is the correct syntax.
    Source = Sql.Database("ABC-PC", "SAMPLEDB", [Query="EXEC DBO.spGetData '" & Name_Value & "'"]
    Thanks
    Dileep

  • 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

  • Creating Query with dynamic columns to show results

    Hi experts,
    I need to know how to create a query with dynamic columns. Meaning, I don't want to create a query with fixed columns representing the 12 periods of the fiscal year to show me actuals as the fiscal year proceeds.
    For example, if I am currently in the middle of period 3 (March) of a fiscal year, when I execute the query, I need it to automatically only show me the 'Actuals' for periods 1 and 2, without seeing the columns from periods 3 to 12 showing blank.
    Then when I am in the middle period 5 (May) the query should ONLY show me the columns for periods 1 to 4 'Actuals', no results should be shown for periods 5 to 12 yet, and I don't want to even see blank columns for period 6 to 12.
    How do I define my columns, to achieve this.
    Maximum points will be awarded.
    Thanks Everyone.

    Hi Josh,
    I'm having a little difficuluty understanding what should be included in my restricted key figures.
    The time characteristics that I have available to use are:
    0FISCPER3 (posting period)
    0FISCYEAR (fiscal year), currently using SAP EXIT to default current fiscal year.
    0FISCVARNT (fiscal year variant).
    In addition, I have the following characteristics available to be used in the columns:
    Value type (10)
    version (currently I'm using variable for it)
    Currency type (020)
    Currency (USD).
    Can you explain what my restricted key figure should be based on and how it should look.
    I tried to create a restircted key figure using 0AMOUNT, and 0FISCPER3. For 0FISCPER3  I created a range from 1 to previous period (using SAP EXIT that supplied previous period).I also had value type, version, currency type, and currency included in that restricted key figure.Then when I tried to drag 0FISCPER3 under the restricted key figure once again, it wouldn't let me, probably because I've already used 0FISCPER3 in the restricted key figure.
    Please let me know if my explanation is not clear.
    Your step by step help would be great.
    Thanks
    Edited by: Ehab Mansour on Sep 23, 2008 2:40 PM

  • Absolute dynamic select query with dynamic join and where

    Has anyone ever tried creating an absolutely dynamic SELECT query with dynamic Join and Where conditions.
    I have a requirement of creating such a query in an Utility Class, and i have written the code. But its throwing my sysntax errors.
    Please let me know where am I going wrong OR is it really possible to create such a dynamic Query??
        SELECT (FIELDS) INTO TABLE IT_TABLES
          FROM ( (ME->TABLE1)  inner join ( me->table2 )
          on ( on_condition ) )
          WHERE (me->where_fields).
    Ags.

    It worked for me in a following way:
    select * into corresponding fields of table <result_table>
            from (join_string)
            where (l_where).
    Where the contents of join_string were dynamically build using concatenation. So it will be something like
    concatenate ME->TABLE1 'as a INNER JOIN' me->table2 'as b ON (' into join_string separated by space.
    <...>
    add here matching/reference colums, something like
    concatenate 'a~' me->TABLE1_JOIN_COL into temp1.
    concatenate 'b~' me->TABLE2_JOIN_COL into temp2.
    concatenate join_string temp1 '=' temp2 into join_string separated by space.
    <...>
    concatenate join_string ')' into join_string separated by space.
    And then use similar approach for l_where variable.

  • Dynamic select query with dynamic where condition

    Hi all,
    I want to use the dynamic select query with dynamic where condition. For that I used the below code but I am getting dump when using this code.
    Please advice, if there is any other way to achieve this requirement.
    Thanks,
    Sanket Sethi
    Code***************
    PARAMETERS: p_tabnam      TYPE tabname,
                p_selfl1      TYPE edpline,
                p_value       TYPE edpline,
                p_where1      TYPE edpline .
    DATA: lt_where    TYPE TABLE OF edpline,
          lt_sel_list TYPE TABLE OF edpline,
          l_wa_name   TYPE string,
          ls_where    TYPE edpline,
          l_having    TYPE string,
          dref        TYPE REF TO data,
          itab_type   TYPE REF TO cl_abap_tabledescr,
          struct_type TYPE REF TO cl_abap_structdescr,
          elem_type   TYPE REF TO cl_abap_elemdescr,
          comp_tab    TYPE cl_abap_structdescr=>component_table,
          comp_fld    TYPE cl_abap_structdescr=>component.
    TYPES: f_count TYPE i.
    FIELD-SYMBOLS : <lt_outtab> TYPE ANY TABLE,
    *                <ls_outtab> TYPE ANY,
                    <l_fld> TYPE ANY.
    struct_type ?= cl_abap_typedescr=>describe_by_name( p_tabnam ).
    elem_type   ?= cl_abap_elemdescr=>describe_by_name( 'F_COUNT' ).
    comp_tab = struct_type->get_components( ).
    comp_fld-name = 'F_COUNT'.
    comp_fld-type = elem_type.
    APPEND comp_fld TO comp_tab.
    struct_type = cl_abap_structdescr=>create( comp_tab ).
    itab_type   = cl_abap_tabledescr=>create( struct_type ).
    l_wa_name = 'l_WA'.
    CREATE DATA dref TYPE HANDLE itab_type.
    ASSIGN dref->* TO <lt_outtab>.
    *CREATE DATA dref TYPE HANDLE struct_type.
    *ASSIGN dref->* TO <ls_outtab>.
    * Creation of the selection fields
    APPEND p_selfl1 TO lt_sel_list.
    APPEND 'COUNT(*) AS F_COUNT' TO lt_sel_list.
    ** Creation of the "where" clause
    *CONCATENATE p_selfl1 '= '' p_value ''.'
    *            INTO ls_where
    *            SEPARATED BY space.
    *APPEND ls_where TO lt_where.
    * Creation of the "where" clause
    APPEND p_where1 TO lt_where.
    * Creation of the "having" clause
    l_having = 'count(*) >= 1'.
    * THE dynamic select
    SELECT          (lt_sel_list)
           FROM     (p_tabnam)
           INTO CORRESPONDING FIELDS OF TABLE <lt_outtab>.
    *       WHERE    (lt_where).

    Hi Sanket,
    The above given logic of mine works for you, put the code in the If condition and try-
    just like below:
    IF NOT P_EBELN IS INITIAL.
    lt_where = '& = ''&'' '.
    REPLACE '&' WITH p_ebeln INTO lt_where.
    REPLACE '&' WITH field_value INTO lt_where.
    SELECT (lt_sel_list) INTO CORRESPONDING FIELDS OF TABLE <lt_outtab>
    FROM (p_tabnam)
    WHERE (lt_where).
    ENDIF.
    thanks\
    Mahesh

  • 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

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

  • 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

  • SSRS - Stored procedure with Dynamic SQL Query

    Am calling stored procedure in SSRS report.  I have used Dynamic SQL query in stored procedure as I don't know the column name and column count.  And I have used like below at end of the stored procedure "select * from ##temptable".
    As I have used dynamic column, am not able to create report with this stored procedure.  Can someone help me out to resolve this issue.
    It will be highly appreciated if I get help. 
    Thanks

    I have tried everything.  But nothing has worked out. 
    If I get solution for below issue, it would be highly appreciated.
    "An error occurred during local report processing.
    The definition of the repport 'Main Report' is invalid.
    The report defintion is not valid.  Details: The report definition has an invalid target namespace 'http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition' which cannot be upgraded.
    Thanks
    Hello,
    I would suggest you post the complete error message to us for further investigation, if you preview the report before you deploy you may get a more detailed error that will help diagnose the source of the problem.
    This issue is more related to SQL Server Reporting Services, it's more appropriate to discuss it in the forum below:
    https://social.technet.microsoft.com/Forums/sqlserver/en-US/home?forum=sqlreportingservices
    Don't forget to elaborate your issue with more detail.
    For the manual column, it might be the calculated field in SSRS. Here is the article for your reference, please see:
    http://technet.microsoft.com/en-us/library/dd239322(v=sql.110).aspx
    Regards,
    Elvis Long
    TechNet Community Support

  • Sql query with dynamic fiscal year

    Hi,
    I wrote this query with static fiscal year and fiscal period, I need info on making the variables dynamic
    Fiscal year : starts from July1st. So this year until June'30 it is '2011' and from July'1st its '2012'
    Fiscal period: July1st its '1' and June'1st its '12'
    Query:
    select distinct o.c_num, o.ac_num, s.sub_ac_num, o.fiscal_year, o.ac_exp_date, s.sub_ac_ind
                             from org_account o
                                  left outer join sub_account s
                                  on o.c_num = s.c_num and o.ac_num = s.ac_num
                             where (o.ac_exp_date >= CURRENT_DATE or o.ac_exp_date is null)
                             and o.fiscal_year = *'2011'* --> need to be dynamic
                             and o.fiscal_period = *'12'* --> need to be dynamic
    thanks,
    Mano
    Edited by: user9332645 on Jun 2, 2011 6:55 PM

    Hi, Mano,
    Welcome to the forum!
    Whenever you have a question, please post a little sample data (CREATE TABLE and INSERT statements), and the results you want from that data.
    Always say which version of Oracle you're using.
    Since this is your first thread, I'll post some sample data for you:
    CREATE TABLE     table_x
    (     dt     DATE
    INSERT INTO table_x (dt) VALUES (DATE '2010-12-31');
    INSERT INTO table_x (dt) VALUES (DATE '2011-01-01');
    INSERT INTO table_x (dt) VALUES (DATE '2011-06-02');
    INSERT INTO table_x (dt) VALUES (DATE '2011-06-30');
    INSERT INTO table_x (dt) VALUES (DATE '2011-07-01');Is this the output you would want from that data?
    DT          FISCAL_YEAR     FISCAL_PERIOD
    31-Dec-2010 2011            06
    01-Jan-2011 2011            07
    02-Jun-2011 2011            12
    30-Jun-2011 2011            12
    01-Jul-2011 2012            01If so, here's one way to get it:
    SELECT       dt
    ,       TO_CHAR ( ADD_MONTHS (dt, 6)
                , 'YYYY'
                )     AS fiscal_year
    ,       TO_CHAR ( ADD_MONTHS (dt, 6)
                , 'MM'
                )     AS fiscal_period
    FROM       table_x
    ORDER BY  dt
    ;Since your fiscal year starts 6 months before the calendar year, you need to add 6 months to the actual date to get the fiscal year and month.
    The query above produces strings for fiscal_year and fiscal_period. If you'd rather have NUMBERs, then use EXTRACT instead of TO_CHAR:
    SELECT       dt
    ,       EXTRACT (      YEAR
                FROM     ADD_MONTHS (dt, 6)
                )     AS fiscal_year
    ,       EXTRACT (      MONTH
                FROM     ADD_MONTHS (dt, 6)
                )     AS fiscal_period
    FROM       table_x
    ORDER BY  dt
    ;The first query will work in Oracle 6 (and higher).
    I'm not sure when EXTRACT was introduced. It definitely works in Oracle 10, and may be available in earlier versions, too.

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

  • Advanced query with dynamic columns

    Hi All,
    I have a table with structure shown below. I need to pull data out of this table and the output should be in a format indicated by the select statement below. I have the following questions and I appreciate if someone could help.
    1. I need to extract 3 years(current year + 2 historical years) worth of data out of this table dynamically(I can't hardcode year). How can I modify the code below so that the select statement returns 3 years worth of data dynamically?
    2. Should I instead calculate each quarter in the select statement using "CASE"? Would this be a good idea and i wouldn't have to deal with the PIVOT function?
    3. The reason I am asking about #2 is because our application requires the out field names to be as CYQ1, CYQ2, CYQ3, CYQ4, LYQ1, LYQ2, LYQ3, LYQ4 etc.(LY = last year). I am not sure if this is possible to do in Pivot table. Could the method outlines
    in #2 be the best practice in my situation?
    Thanks in advance for your thoughts.
    DECLARE @Trans_Summary TABLE(
    [Account_ID] [int] NULL,
    [End_Date] DATE NULL,
    [Amount] [float] NULL,
    [Customer_ID] [int] NULL)
    INSERT @Trans_Summary VALUES(1, '03/31/2013', 100, 123)
    INSERT @Trans_Summary VALUES( 1, '01/31/2013', 200, 123)
    INSERT @Trans_Summary VALUES( 1, '06/30/2013', 100, 123)
    INSERT @Trans_Summary VALUES( 1, '09/30/2013', 100, 123)
    INSERT @Trans_Summary VALUES( 1, '12/31/2013', 100, 123)
    SELECT *
    FROM @Trans_Summary
    PIVOT(SUM([Amount])FOR End_Date IN ([2013-01-31], [2013-03-31], [2013-06-30], [2013-09-30], [2013-12-31])) AS TT

    Yes, you should always use CASE for pivots and never use the PIVOT keyword. The latter gives you somewhat shorter query text, for very little gain.
    As I understand what you are asking for, you can easily do it with CASE without dynamic SQL:
    DECLARE @year char(4) = '2013',
            @q1 = char(4) = '0331',
            @q2 = char(4) = '0630',
            @q3 = char(4) = '0930',
            @q4 = char(4) = '1231'
    SELECT Account_ID,
           SUM(CASE WHEN End_Date = @year + @q1 THEN Amount END) AS CYQ1,
           SUM(CASE WHEN End_Date = dateadd(YEAR, -1, @year + @q1) THEN Amount END) AS LYQ1,
    FROM   tbl
    GROUP  BY Account_ID
    Well, maybe that can be done with PIVOT as well, but I have never learnt how to use the keyword. It just looks difficult to me. And useless.
    Erland Sommarskog, SQL Server MVP, [email protected]

Maybe you are looking for

  • Locking Selected Fields on Submit

    Hello, I've been working on a multiple-item quote request form. My intention is that Party A (Requestor) will fill in the item description and details necessary for Party B (Vendor) to provide a quote. The form will be emailed to the Vendor who will

  • Install NTOP 3.2 in Solaris 10 Intel !

    Hi everybody ! I need help to install NTOP 3.2 in Solaris 10 INTEL i am having problems with the libraries pcap, libcap... I have been installing all the packages of the companion and I also compiled the libcap, i placed in my profile all the possibl

  • How to convert General sales orders to Duplicate one

    Hi all i want to know about duplicate sales orders ... How to convert sales orders into duplicate sales orders i know we can check in SDD1 Table but i want like to know how to convert General sales orders to Duplicate one Thanks a lot

  • ASSIGN_CASTING_ILLEGAL_CAST

    Hi All, In BW 7.40, I am getting following dump while running DTP from data source 0MATERIAL_ATTR to 0MATERIAL. First time error...not sure, someone please shed some light on this !!! regards,

  • Velocity Function Not Working

    Working on a new project and encompassed a small issue. I dropped some hi-hats into a track and was trying to alter the velocity. It's a one bar region with 2 hits at 127 Velocity and two at a lower Velocity (let's say 97). Trying to create more of a