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

Similar Messages

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

  • 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

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

  • I want to transfer my photo and movie files from my iPhone 4S to my mac.

    I have posted this question before without any success and was hoping by reposting it may promt a solution to my problem.
    I want to transfer my photo and movie files from my iPhone to my Mac OS X (10.5.8).
    But I don't want to use Cloud or iTunes.
    Is there a way to connect my iPhone 4S to my Mac directly,
    say ... via a program or such on my MAC, to drag and drop the photos and Movie files,
    directly into a folder. ??????????
    Reason want to connect iPone to MAC or MAC to iPhone is ....
    I have no DATA on my iPhone Mobile plan at moment.
    So Photosync app is no good, as I can't download the app to my iPhone.
    I can download a Photosync to my MAC ...
    but with the Photosync app you can only send data.
    Thanks in advance for any help.

    Sorry I should of mentioned ....
    Reason want to connect iPone to MAC or MAC to iPhone is ....
    I have no DATA on my iPhone plan at moment.
    So Photosync app is no good, as I can't download the app to my iPhone.
    I can download a Photosync to my MAC ...
    but with the Photosync app you can only send data  (so needs to be on the  iPhone).

  • 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

  • ERROR creating table with dynamic SQL :-(

    Hi friends,
    I have a problem when I try to create a table using dynamic SQL.
    (Env.: Forms 6i, WinXP, Oracle 9i)
    I only want to create a table, insert data and drop the table.
    I have a user with the correct privileges (At least ....I think so), because I can to make the three actions in SQL*PLUS (CREATE TABLE, INSERT .. and DROP TABLE).
    I want to do the same in Forms using dynamic SQL...
    I've made a package with 3 procedures:
    1st to create the table, 2nd to insert data , 3rd to drop the table.
    Only the 1st fails with the error ORA-01031 (insufficient privileges).
    Here it is:
    PROCEDURE PRO_DM_CreaTabla(pe_nombre_tabla VARCHAR2) IS
    id_cursor INTEGER;
    ls_sentencia VARCHAR2(500);
    v_dummy integer;
    BEGIN
    id_cursor := DBMS_SQL.OPEN_CURSOR;
    ls_sentencia := 'CREATE TABLE '||pe_nombre_tabla||' ( campo1 VARCHAR2(100), campo2 VARCHAR2(100), campo3 VARCHAR2(100),campo4 VARCHAR2(100))';
    DBMS_SQL.PARSE(id_cursor, ls_sentencia, dbms_sql.NATIVE);
    v_dummy := dbms_sql.execute(id_cursor);
    DBMS_SQL.CLOSE_CURSOR(id_cursor);
    END;
    The DROP_table procedure is exactly the same as this (with the difference of the 'CREATE' sentence, where I have a DROP sentence)... then.. why the DROP procedure works?... and.. why this CREATE procedure doesn't work?
    Any ideas?
    Thanks a lot.
    Jose.

    From a different thread, Jose wrote:
    V_INSERT:='INSERT INTO TMP_TABLE(field1,field3,field3,field4) VALUES (1,2,3,4)';
    Forms_DDL(V_INSERT);
    commit;First, try your statement in SQL Plus:
    INSERT INTO TMP_TABLE(field1,field3,field3,field4) VALUES (1,2,3,4);
    Then if that works, try doing this right after the Forms_DDL(V_INSERT);
    If not form_success then
      Message('   Insert has failed');
      Raise form_trigger_failure;
    Else
      Forms_DDL('COMMIT');
    End if;

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

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

  • 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

  • LOV with dynamic SQL

    Hi everyone
    I would like to have an LOV that returns the list based on a dynamic SQL statement based on page items.
    Example:
      :P1_ID_COLNAME    := 'empno';
      :P1_VALUE_COLNAME := 'name';
      'SELECT ' || :P1_VALUE_COLNAME || ', ' || :P1_ID_COLNAME || ' FROM emp;'resulting in
      SELECT name, empno FROM emp;My PL/SQL skills are fairly limited. However, my assumption would be to use EXECUTE IMMEDIATE within a function and returning a REF CURSOR containing the dynamic query.
    Do you agree with that? Or have you even got other ideas?
    Appreciate your thoughts.
    Regards,
    Michael

    I've found the solution myself.
    It's even easier than I thought:
    APEX allows a LOV source to be a VARCHAR2 return value of a function:
    LOV source
    RETURN f_get_query(:P1_VALUE_COLNAME, :P1_ID_COLNAME);
    function on DB
    FUNCTION f_get_query(
        in_value_colname VARCHAR2,
        in_id_colname VARCHAR2
    RETURN VARCHAR2
    IS
    BEGIN
      RETURN 'SELECT ' || in_value_colname || ', ' || in_id_colname || ' FROM emp;';
    END;Michael

  • Problems while creating a Java stored proc with dynamic SQL

    Hi,
    I am trying to write a stored procedure which uses dynamic SQL. The code runs fine outside the database (on DOS PROMPT),but gives me an exception when I try to execute it as a procedure. Could somebody help me out?
    The exception given is:
    ERROR at line 1:
    ORA-29532: Java call terminated by uncaught Java exception:
    java.security.AccessControlException: the Permission (java.net.SocketPermission
    elcamino.mcasolutions.com resolve) has not been granted by
    dbms_java.grant_permission to SchemaProtectionDomain(SPO|PolicyTableProxy(SPO))
    Does it have anything to access permissions to that user?
    Thanks in advance!
    Joe

    Hi:
    This store procedure is a Java stored procedure (JSP)?
    If true, change your Java code to connect to database because you are connected.
    For example:
    Connection con = new OracleDriver().defaultConnection();
    instead of
    Connection con = DriverManager.getConnection(..);
    Bye.
    J.

  • 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
              

  • An issue with Dynamic SQL within Package using REF CURSOR

    Hi there,
    In the following package first two procedures works file but since I have added the third one ( GET_CONTRACT_BY_DYN_SQL) it does not work for me. When I try to compile and save it gives below error.
    "Error(6,15): PLS-00323: subprogram or cursor 'GET_CONTRACT_BY_DYN_SQL' is declared in a package specification and must be defined in the package body"
    Can you please help?
    Package Header
    create or replace
    PACKAGE CONTRACTS_PKG AS
    TYPE T_CURSOR IS REF CURSOR;
    PROCEDURE GET_CONRACTS (IO_CURSOR IN OUT T_CURSOR);
    PROCEDURE GET_CONTRACT_BY_ID (I_CONTRACTID IN NUMBER, IO_CURSOR IN OUT T_CURSOR);
    PROCEDURE GET_CONTRACT_BY_DYN_SQL(P_CONTRATID IN NUMBER, P_COLS IN VARCHAR2, IO_CURSOR IN OUT T_CURSOR);
    END CONTRACTS_PKG;
    Package Body
    create or replace
    PACKAGE BODY CONTRACTS_PKG AS
    -- Get All Contracts
    PROCEDURE GET_CONRACTS(IO_CURSOR IN OUT T_CURSOR)
    IS
    V_CURSOR T_CURSOR;
    BEGIN
    OPEN V_CURSOR FOR
    SELECT * FROM CONTRACTS;
    IO_CURSOR := V_CURSOR;
    END GET_CONRACTS;
    -- Get Contract By ID
    PROCEDURE GET_CONTRACT_BY_ID(I_CONTRACTID IN NUMBER, IO_CURSOR IN OUT T_CURSOR)
    IS
    V_CURSOR T_CURSOR;
    BEGIN
    OPEN V_CURSOR FOR
    SELECT * FROM CONTRACTS WHERE contract_id = I_CONTRACTID;
    IO_CURSOR := V_CURSOR;
    END GET_CONTRACT_BY_ID;
    -- Get Contract Using Dynamic SQL
    PROCEDURE GET_CONTRACT_BY_DYN_SQL(P_CONTRACTID IN NUMBER, P_COLS IN VARCHAR2, IO_CURSOR IN OUT T_CURSOR)
    IS
    V_CURSOR T_CURSOR;
    V_SQL VARCHAR2(200);
    BEGIN
    V_SQL := 'SELECT '|| P_COLS || ' FROM CONTRACTS WHERE contract_id = ' || P_CONTRACTID ;
    --OPEN V_CURSOR FOR
    --EXECUTE IMMEDIATE V_SQL INTO V_CURSOR;
    OPEN V_CURSOR FOR V_SQL;
    EXECUTE IMMEDIATE V_SQL;
    --IO_CURSOR := V_CURSOR;    
    END GET_CONTRACT_BY_DYN_SQL;
    END CONTRACTS_PKG;
    Thanks in advance.
    Hitesh

    Thanks guys. Finally I have tweaked as per your suggestions and it's working for all 3 cases (stored procedures).
    Oracle
    ======
    Package Header
    create or replace
    PACKAGE CONTRACTS_PKG AS
    TYPE T_CURSOR IS REF CURSOR;
    PROCEDURE GET_CONRACTS (IO_CURSOR IN OUT T_CURSOR);
    PROCEDURE GET_CONTRACT_BY_ID (I_CONTRACTID IN NUMBER, IO_CURSOR IN OUT T_CURSOR);
    PROCEDURE GET_CONTRACT_BY_DYN_SQL(P_CONTRACTID IN NUMBER, P_COLS IN VARCHAR2, IO_CURSOR IN OUT T_CURSOR);
    END CONTRACTS_PKG;
    Package Body
    create or replace
    PACKAGE BODY CONTRACTS_PKG AS
    -- Get All Contracts
    PROCEDURE GET_CONRACTS(IO_CURSOR IN OUT T_CURSOR)
    IS
    V_CURSOR T_CURSOR;
    BEGIN
    OPEN V_CURSOR FOR
    SELECT * FROM CONTRACTS;
    IO_CURSOR := V_CURSOR;
    END GET_CONRACTS;
    -- Get Contract By ID
    PROCEDURE GET_CONTRACT_BY_ID(I_CONTRACTID IN NUMBER, IO_CURSOR IN OUT T_CURSOR)
    IS
    V_CURSOR T_CURSOR;
    BEGIN
    OPEN V_CURSOR FOR
    SELECT * FROM CONTRACTS WHERE contract_id = I_CONTRACTID;
    IO_CURSOR := V_CURSOR;
    END GET_CONTRACT_BY_ID;
    -- Get Contract Using Dynamic SQL
    PROCEDURE GET_CONTRACT_BY_DYN_SQL(P_CONTRACTID IN NUMBER, P_COLS IN VARCHAR2, IO_CURSOR IN OUT T_CURSOR)
    IS
    V_CURSOR T_CURSOR;
    V_SQL VARCHAR2(200);
    BEGIN
    IF p_contractid > 0 THEN
    V_SQL := 'SELECT '|| P_COLS || ' FROM CONTRACTS WHERE contract_id = ' || P_CONTRACTID ;
    ELSE
    V_SQL := 'SELECT '|| P_COLS || ' FROM CONTRACTS';
    END IF;
    OPEN V_CURSOR FOR V_SQL;
    IO_CURSOR := V_CURSOR;
    END GET_CONTRACT_BY_DYN_SQL;
    END CONTRACTS_PKG;
    ColdFusion (calling app code)
    =====================
    <cfstoredproc procedure="CONTRACTS_PKG.GET_CONTRACT_BY_ID" datasource="#REQUEST.dsn#">
         <cfprocparam cfsqltype="CF_SQL_INTEGER" type="in" value="1" variable="I_CONTRACTID">
         <cfprocresult name="qData" resultset="1">
    </cfstoredproc>
    <br>Single Contract:
    <cfdump var="#qData#" label="Single Contract">
    <cfstoredproc procedure="CONTRACTS_PKG.GET_CONRACTS" datasource="#REQUEST.dsn#">     
         <cfprocresult name="qDataAll" resultset="1">
    </cfstoredproc>
    <br>All Contracts:
    <cfdump var="#qDataAll#" label="All Contracts">
    <cfstoredproc procedure="CONTRACTS_PKG.GET_CONTRACT_BY_DYN_SQL" datasource="#REQUEST.dsn#">
         <cfprocparam cfsqltype="CF_SQL_INTEGER" type="in" value="1" variable="P_CONTRACTID">
         <cfprocparam cfsqltype="CF_SQL_VARCHAR" type="in" value="contract_number,contract_title,created_date" variable="P_COLS">
         <cfprocresult name="qDataDynSQL" resultset="1">
    </cfstoredproc>
    <br>Dynamic SQL Query:
    <cfdump var="#qDataDynSQL#" label="Dynamic SQL Query">
    Thanks,
    Hitesh Patel

Maybe you are looking for

  • Hiding  a Equipment  view  in a  transaction iq01

    Hai Friends,              How to hide a Equipment view in a transation for create material serial number (iq01). Regards, Sathis Kumar R

  • Force "Require password" option

    Just curious if there is a way to not allow the user to change the "Require password" option (Security Prefs/General) in Lion (10.7.3). If I make the user managed by the server I could disable the pane, but I'd rather than do that in this case. Any w

  • Canoscan Lide 200 will not start

    After upgrading to Yosemite, when I plug in my USB-driven Canon scanner (into my Macbook Air from 2010) I get an error message advising that "a problem" occurred. Anyone else finding that a Canoscan Lide scanner will not start in Yosemite? Any sugges

  • IS THERE A GRACE PERIOD ON LATE PAYMENT

    my bill is due next sunday but i'm not going to have the money for the bill until that friday [5 days after the due date]. is there any grace period for payment? i've made all my payments on time since i've started my own verizon bill.

  • ICal events have duplicated, now disappearing in front of my very eyes? What's up

    Yesterday I opened iCal on my MacBook Pro to find that all my events were duplicated; today, some of them are totally gone and some are disappearing in front of my very eyes. Today, there is a new calendar listed at the left for my .me account, a dup