Drop table if exists in sql statement

Oracle: 10G
Is there a way to check if table exist and then only drop table. Something like:
drop table (select table_name from user_tables where lower(table_name) = 'o2i_filing_dest')

As already suggested, you could e.g. use an anonymous PL/SQL block as part of your SQL script, e.g. something like that:
set echo on
spool <your_log_file>
WHENEVER SQLERROR EXIT FAILURE
DECLARE
  PROCEDURE EXEC_DONT_FAIL( P_CMD IN VARCHAR2 ) IS
    e_table_or_view_does_not_exist exception;
    pragma exception_init(e_table_or_view_does_not_exist, -942);
    e_type_does_not_exist exception;
    pragma exception_init(e_type_does_not_exist, -4043);
    e_sequence_does_not_exist exception;
    pragma exception_init(e_sequence_does_not_exist, -2289);
  BEGIN
    EXECUTE IMMEDIATE P_CMD;
  EXCEPTION
  WHEN e_table_or_view_does_not_exist OR e_type_does_not_exist OR e_sequence_does_not_exist THEN
      NULL;
  END;
BEGIN
  EXEC_DONT_FAIL('drop type <type_name1> force');
  EXEC_DONT_FAIL('drop view <view_name1>');
  EXEC_DONT_FAIL('drop table <table_name1> purge');
  EXEC_DONT_FAIL('drop sequence <seq_name1>');
END;
CREATE TABLE ...Note that the literals in angle brackets are just placeholders for demonstration purposes, you need to use your actual object names/file names there.
Of course you could also use a FOR ... LOOP in the PL/SQL block that queries e.g. USER_OBJECTS to find out which objects to drop.
That way it is ensured that only expected exceptions will be ignored but all others will raise and stop your script in that case.
Regards,
Randolf
Oracle related stuff blog:
http://oracle-randolf.blogspot.com/
SQLTools++ for Oracle (Open source Oracle GUI for Windows):
http://www.sqltools-plusplus.org:7676/
http://sourceforge.net/projects/sqlt-pp/
Edited by: Randolf Geist on Sep 25, 2008 10:09 AM
Clarification regarding angle brackets added

Similar Messages

  • SQL or PL/SQL : dynamically insert table name in a SQL Statement

    Hi,
    We have a strange requirement - we need to dynamically use the table names in a SQL Query. E.g:
    select * from :table_name
    The table_name will be chosen from a list. I have tried this in SQL as well as PL SQL - but, I have been unsuccessul so far.
    Can you guys please help me solve this puzzle ?
    I hope I have explained my quesion clearly - if not, please do let me know if some more details are necessary.
    Regards,
    Ramky

    The following is the anonymous block that im using in a report in HTMLDB. My problem is Line Number 9. The bind variable contains the chosen table name at
    the run time.
    Variable "qry_stmt" contains the query to be returned, so that result set for that query will be displayed in the report.
    If I hard code the table name(rather that passing it through bind variable) in the
    qry_stmt string, Im getting the result sets for that query. But if I pass through
    bind variable at run time, its still generating the string correctly( im printing
    using a print statement at line number 14). But its returing the following report
    error
    report error:
    ORA-01403: no data found
    Please advice/help me in this.....
    declare
    qry_stmt varchar2(1000);
    p_table varchar2(30) := 'EMP';
    P_ENAME varchar2(1000);
    begin
    IF :p2_TABLE_NAMES IS NOT NULL THEN
    qry_stmt := 'select * from '||TRIM(:P2_TABLE_NAMES); -- Line Num 9
    execute immediate qry_stmt; --into P_ENAME;
    ELSE
    qry_stmt := 'SELECT 1 FROM dual ';
    END IF;
    htp.p(qry_stmt);--Line Num 14
    return qry_stmt;
    EXCEPTION WHEN NO_DATA_FOUND THEN
    NULL;
    end;
    Thanks and Regards,
    Ramky

  • DROP TABLE works through SSMS but not via T-SQL Query

    Hello All,
    I am trying to drop a number of tables (1,000+) in a particular database by scripting the actions in T-SQL. When I run the query I get error 3701 on every table which points to a permissions issue. However, I am able to delete tables one by one using
    the tree-view in the SSMS Object Explorer. 
    1. I have tried starting query sessions with both the DBO of the database and the SA account to no avail. (Both had the sysadmin role when I tried.)
    2. Both the DBO account and the SA account are able to drop tables using SSMS Object Explorer.
    Do I need a specific GRANT of permissions to use T-SQL versus SSMS or am I missing something even more fundamental?
    TIA, Simon
    <code>
    DECLARE @Company VARCHAR(max), 
    @ID VARCHAR(max), 
    @NAME VARCHAR(max), 
    @TABLE_CATALOG VARCHAR(max),
    @NAV_DATABASE VARCHAR(max),
    @TABLE_NAME VARCHAR(max), 
    @STATEMENT VARCHAR(max),
    @OBJECT_NAME VARCHAR(max),
    @OBJECT_NAME_BARE VARCHAR(max),
    @OBJECT_TYPE VARCHAR(max);
    SET @TABLE_CATALOG = 'NAV_PENTA_TEST_GAAP';
    SET @NAV_DATABASE = @TABLE_CATALOG
    IF @TABLE_CATALOG <> DB_NAME() 
    BEGIN
    DECLARE @ERRORMSG VARCHAR(max);
    SET @ERRORMSG =  'You are not in the correct database. You specified ' + @TABLE_CATALOG + ' but you are currently in a session for ' + db_name();
    RAISERROR(@ERRORMSG, 18, 1);
    RETURN;
    END;
    -- To hold the object names (tables) from Navision
    CREATE TABLE #NavisionObjects
    [CompanyName]
    VARCHAR(max),
    [ID] VARCHAR(max),
    [Name]
    VARCHAR(max),
    [TABLE_NAME]
    VARCHAR(max)
    -- To hold the object names (tables) from SQL only
    CREATE TABLE #NavisionSQLObjects
    [TABLE_NAME]
    VARCHAR(max)
    -- Holds the list of dependent objects
    CREATE TABLE #DependentObjects
    [name] VARCHAR(max),
    [type] VARCHAR(max)   
    WITH T AS (
    SELECT [Company Name],[ID],[Name],[Company Name]+'$'+[Name] AS TABLE_NAME 
    FROM [Object]   
    WHERE [Name] like '%IT IS%' AND [Company Name]>''
    UNION ALL
    SELECT [Company Name],[ID],[Name],[Name] AS TABLE_NAME 
    FROM [Object]   
    WHERE [Name] like '%IT IS%' AND [Company Name] IN ('',' ')
    INSERT INTO #NavisionObjects SELECT [Company Name],[ID],[Name],[TABLE_NAME] FROM T;
    UPDATE #NavisionObjects SET TABLE_NAME = TABLE_NAME+ID WHERE ID LIKE '1%';
    INSERT INTO #NavisionSQLObjects 
    SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_CATALOG = @TABLE_CATALOG AND TABLE_NAME LIKE '%IT IS%' AND TABLE_TYPE='BASE TABLE';
    --SELECT * FROM #NavisionObjects where CompanyName like 'E15%' order by TABLE_NAME;
    --SELECT * FROM #NavisionSQLObjects where TABLE_NAME like 'E15%' order by TABLE_NAME;
    DECLARE cTables CURSOR FOR SELECT A.CompanyName,A.ID,A.[TABLE_NAME] FROM #NavisionObjects A
    INNER JOIN #NavisionObjects B ON B.[TABLE_NAME]=A.[TABLE_NAME]
    OPEN cTables;
    FETCH NEXT FROM cTables INTO @Company,@ID,@TABLE_NAME;
    WHILE (@@FETCH_STATUS = 0)
    BEGIN
    PRINT 'Storing dependencies for [' + @TABLE_NAME + ']';
    BEGIN TRY
    INSERT INTO #DependentObjects 
    EXEC sp_depends @TABLE_NAME;
    END TRY
    BEGIN CATCH
    PRINT 'Could not get dependencies for table [' + @TABLE_NAME + ']';
    END CATCH
    FETCH NEXT FROM cTables INTO @Company,@ID,@TABLE_NAME;
    END
    CLOSE cTables;
    Drop dependent objects first so that table drops are less likely to fail. 
    DECLARE cdo CURSOR FOR SELECT [Name],[Type] FROM #DependentObjects;
    OPEN cdo;
    FETCH NEXT FROM cdo INTO @OBJECT_NAME, @OBJECT_TYPE;
    WHILE (@@FETCH_STATUS = 0)
    BEGIN
    BEGIN TRY
    SET @OBJECT_NAME_BARE = 
    CASE 
    WHEN CHARINDEX('dbo',@OBJECT_NAME) = 1
    THEN RIGHT(@OBJECT_NAME,LEN(@OBJECT_NAME)-4)
    ELSE @OBJECT_NAME
    END;
    SET @STATEMENT = 'DROP ' + @OBJECT_TYPE + ' [' + @OBJECT_NAME_BARE + ']';
    PRINT @STATEMENT;
    EXEC sys.sp_sqlexec @STATEMENT;
    END TRY
    BEGIN CATCH
    PRINT 'Could not DROP object [' + @OBJECT_NAME + '] of type ' + @OBJECT_TYPE + ', SQL Error ' + CAST(@@ERROR AS VARCHAR(max));
    END CATCH
    FETCH NEXT FROM cdo INTO @OBJECT_NAME, @OBJECT_TYPE;
    END
    CLOSE cdo;
    DEALLOCATE cdo;
    OPEN cTables;
    FETCH NEXT FROM cTables INTO @Company,@ID,@TABLE_NAME;
    WHILE (@@FETCH_STATUS = 0)
    BEGIN
    PRINT 'Removing [' + @TABLE_NAME + ']' ;
    BEGIN TRY
    SET @STATEMENT = 'TRUNCATE TABLE dbo.[' + @TABLE_NAME + ']';
    PRINT @STATEMENT;
    EXEC sys.sp_sqlexec @STATEMENT;
    END TRY
    BEGIN CATCH
    PRINT 'Could not truncate table [' + @TABLE_NAME + ']';
    END CATCH
    BEGIN TRY
    SET @STATEMENT = 'DROP TABLE dbo.[' + @TABLE_NAME + ']';
    PRINT @STATEMENT;
    EXEC sys.sp_sqlexec @STATEMENT;
    BEGIN TRY
    SET @STATEMENT = 'DELETE FROM [Object] WHERE [Company Name] = ' + CHAR(39) + @Company + CHAR(39) + ' AND [ID] = ' + CHAR(39) + @ID + CHAR(39) + ' AND [TABLE_NAME] = ' + CHAR(39) +
    @TABLE_NAME + CHAR(39) ;
    EXEC sys.sp_sqlexec @STATEMENT;
    print @STATEMENT;
    END TRY
    BEGIN CATCH
    PRINT 'Could not Delete Object [' + @TABLE_NAME + '], from Object table, SQL Error ' + CAST(@@ERROR AS VARCHAR(max));
    END CATCH
    END TRY
    BEGIN CATCH
    PRINT 'Could not DROP table [' + @TABLE_NAME + '], SQL Error ' + CAST(@@ERROR AS VARCHAR(max));
    END CATCH
    FETCH NEXT FROM cTables INTO @Company,@ID,@TABLE_NAME;
    END
    CLOSE cTables;
    DEALLOCATE cTables;
    DROP TABLE #DependentObjects;
    DROP TABLE #NavisionObjects;
    DROP Table #NavisionSQLObjects;
    </code>

    3701 = ...does not exist or you don't have permission.
    Most of the time it means the former. So there are probably some problems in your DROP TABLE statements. Since there is a whole lot about Navision in the script, I decline from trying to figure out what. But I encourage you to study the PRINT statements.
    I think that it would be a good idea to include the schema name, in cases these tables are not in dbo after all.
    Note: rather than writing:
       SET @STATEMENT = 'DROP ' + @OBJECT_TYPE + ' [' + @OBJECT_NAME_BARE + ']';
    write:
       SET @STATEMENT = 'DROP ' + @OBJECT_TYPE + quotename(@OBJECT_NAME_BARE)
    Somewhat briefer. And it works also when the object name includes a right bracket.
    sp_sqlexec is undocumented, use sp_executesql instead.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • How to process sql statements stored in a table

    I have a rule table that contain rule_type, rule_status and rule_condition. The rule condition is a sql statement. In a report I need to be able to expand this condtion based on the status selected. E.g When rule status is terminated the rule_condition is as below. When a user pick terminated status, I need to be able to go to the table and expand the sql statement. Another example is active status.
    RULE_STATUS TERMINATED
    SELECT leaseid
    FROM leatatt
    WHERE txtattid = 'LEAS END'
    and value = 'TERMINATED'
    RULE_STATUS ACTIVE
    SELECT leaseid
    FROM lease
    WHERE redoc_class = 'MASTER'
    AND TRUNC(SYSDATE) <=
    NVL(TRUNC(enddate),TRUNC(SYSDATE)+1)
    AND functional_status IN ('ACTIVE','OVERHOLD')
    Any suggestion will be appreciated.

    Please refer to
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:246014735810
    I am sure you would be twist this to bring it in to your use.
    <PRE>
    the proper way to do this is to NOT use a PLSQL table type but to use a SQL Object Type
    instead. It would look like this:
    [email protected]> create or replace type myScalarType as object
    2 ( x int,
    3 y date,
    4 z varchar2(25)
    5 )
    6 /
    Type created.
    [email protected]> create or replace type myTableType as table of myScalarType;
    2 /
    Type created.
    [email protected]> create or replace
    2 function demo_proc( p_start_row in number,
    3 p_end_row in number )
    4 return myTableType
    5 as
    6 l_data myTableType := myTableType();
    7 l_cnt number default 0;
    8 begin
    9 for x in ( select * from emp order by sal desc )
    10 loop
    11 l_cnt := l_cnt + 1;
    12 if ( l_cnt >= p_start_row )
    13 then
    14 l_data.extend;
    15 l_data(l_data.count) :=
    16 myScalarType( x.empno,
    17 x.hiredate,
    18 x.ename );
    19 end if;
    20 exit when l_cnt = p_end_row;
    21 end loop;
    22
    23 return l_data;
    24 end;
    25 /
    Function created.
    [email protected]> select *
    2 from the ( select cast( demo_proc(2,6) as mytableType )
    3 from dual ) a
    4 /
    X Y Z
    7788 09-DEC-82 SCOTT
    7902 03-DEC-81 FORD
    7566 02-APR-81 JONES
    7698 01-MAY-81 BLAKE
    7782 09-JUN-81 CLARK
    [email protected]>
    </PRE>

  • Sql statement for a table name with a space in between

    Hi,
    I just noticed that one of my tables for Access is consisted of two word. It is called "CURRENT CPL". How would I put this table name into an sql statement. When I did what I normally do, it only reads the CURRENT and thinks that's the table name.
    Thanks
    Feng

    I just noticed that one of my tables for Access is
    consisted of two word. It is called "CURRENT CPL".
    How would I put this table name into an sql
    statement. When I did what I normally do, it only
    reads the CURRENT and thinks that's the table name.That is called a quoted identifier. The SQL (not java) for this would look like this....
    select "my field" from "CURRENT CPL"
    The double quote is the correct character to use. Note that quoted identifiers are case sensitive, normal SQL is not.

  • Cannot drop table

    Versions are Oracle 11.2.0.1.0 and SQL Developer 4.0.0.12 on Windows 7 Ultimate SP1.
    Hi
    I'm following the CBT Nuggets SQL Fundementals training (video #11) and cannot drop a table I have just created.  The command executed and error are:
    drop table newprods;
    Error starting at line : 1 in command -
    drop table newprods
    Error report -
    SQL Error: ORA-00604: error occurred at recursive SQL level 1
    ORA-20000: Cannot drop object
    ORA-06512: at line 2
    00604. 00000 -  "error occurred at recursive SQL level %s"
    *Cause:    An error occurred while processing a recursive SQL statement
               (a statement applying to internal dictionary tables).
    *Action:   If the situation described in the next error on the stack
               can be corrected, do so; otherwise contact Oracle Support.
    As the HR user I created two tables and created a FK constraint between them.  After truncating the table with this FK, I am unable to drop it.  Even if I remove the FK, the error is the same.  Issing the command in SQL*Plus gives the same error.
    This is the first time I have created any tables since installing Oracle on this machine and is my first attempt at dropping a table.  I have not created any sequences, triggers or views based on these newly created tables.
    Does anyone have any ideas?
    Cheers

    C:\Oracle>sqlplus hr@orcl
    SQL*Plus: Release 11.2.0.1.0 Production on Wed Sep 4 18:58:55 2013
    Copyright (c) 1982, 2010, Oracle.  All rights reserved.
    Enter password:
    Connected to:
    Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    SQL> CREATE TABLE table1 (column1 VARCHAR2(20 BYTE));
    Table created.
    SQL> select * from table1;
    no rows selected
    SQL> drop table table1;
    drop table table1
    ERROR at line 1:
    ORA-00604: error occurred at recursive SQL level 1
    ORA-20000: Cannot drop object
    ORA-06512: at line 2
    SQL>
    Can I run a query to see if there are any triggeres on the table?
    EDIT: Ok it looks like no triggers:
    SQL> show user
    USER is "SYS"
    SQL> select * from DBA_TRIGGERS where table_name like '%table1%';
    no rows selected
    SQL> select * from USER_TRIGGERS where table_name like '%table1%';
    no rows selected

  • How to Create new database (copy all table with data excluding 2 table )with existing database.

    Please follow the scenario:
    using C#
    1) current database file name is DB20122013.
    when user click on new year button
    2)Create backup copy of current database
    3)New database should create with all table(excluding table "Dailytemp" and "DailyMain") with data and database name as DB20132014.
    Musakkhir Sayyed.

    Hi,
    I hope, below stored procedure is useful for your scenario.
    CREATE PROC Create_New_Database
    ( @DBNAME VARCHAR(550)
    )AS
    Test : Exec [Create_New_Database] @DBNAME='DB20122013'        
    BEGIN TRY               
    SET NOCOUNT ON   
    DECLARE @sql VARCHAR(MAX), @DBNAME_NEW VARCHAR(550),@num int
    IF EXISTS(SELECT 1 FROM sys.databases WHERE name=@DBNAME) AND ISNUMERIC(RIGHT(@DBNAME,4))=1
    BEGIN
    SELECT @num= RIGHT(@DBNAME,4) 
    SELECT @DBNAME_NEW='DB'+CAST(@num AS VARCHAR(10))+''+CAST(@num+1 AS VARCHAR(10)) 
    IF EXISTS(SELECT 1 FROM sys.databases WHERE name=@DBNAME_NEW)
    BEGIN
    SELECT @DBNAME_NEW+' database already exists'
    END
    ELSE
    BEGIN
    SET @sql='USE '+@DBNAME+'  '+' backup database '+@DBNAME+' to disk = ''C:\'+@DBNAME+'.bak''  '
    +' restore database '+@DBNAME_NEW+' from disk = ''C:\'+@DBNAME+'.bak'''
    +' with move '''+@DBNAME+''' to ''C:\'+@DBNAME+'_data.mdf'' ,
    move '''+@DBNAME+'_log'' to ''C:\'+@DBNAME+'_log.log'''
    EXEC (@sql)
    SET @sql=''
    SET @sql=' USE '+@DBNAME_NEW+' IF EXISTS(SELECT 1 FROM SYS.TABLES WHERE NAME=''Dailytemp'') 
    BEGIN DROP TABLE Dailytemp END IF EXISTS(SELECT 1 FROM SYS.TABLES WHERE NAME=''DailyMain'') 
    BEGIN DROP TABLE DailyMain END '
    EXEC (@sql)
    END  
    END
    ELSE 
    BEGIN
    SELECT 'Database is now found or Database name does not mach the scenario'
    END
    SET NOCOUNT OFF   
    END TRY   
    BEGIN CATCH                
     DECLARE @ErrorMessage NVARCHAR(4000)                
        DECLARE @ErrorSeverity INT                
        DECLARE @ErrorState INT                           
        SELECT @ErrorMessage = ERROR_MESSAGE(), @ErrorSeverity = ERROR_SEVERITY(),@ErrorState = ERROR_STATE()                
        RAISERROR (@ErrorMessage,@ErrorSeverity,@ErrorState )                
    END CATCH;   
    GO
    Regards,
    RAMBHARATH

  • Drop table for multiple tables

    Hi All,
    I want to drop multiple tables in one drop statement.
    Can it be possible?
    Thanks in advance!!
    SA

    Hi,
    CASCADE CONSTRAINTS must be taken into account. E.g.,
    set pages 0
    spool c:\windows\temp\drop.sql
    select 'DROP TABLE '||TABLE_NAME || ' CASCADE CONSTRAINTS;' from user_tables WHERE table_name like 'ZTEST%';
    spool off
    @c:\windows\temp\drop.sqlHere is a test case:
    SQL> set echo off
    SQL> create table ztest1 (ff NUMBER PRIMARY KEY);
    Table created
    SQL> insert into ztest1 select 1 from dual;
    1 row inserted
    SQL> create table ztest2 (gg NUMBER, constraint gg_fk foreign key (gg) references ztest1(ff));
    Table created
    SQL> insert into ztest2 select 1 from dual;
    1 row inserted
    SQL> drop table ztest1;
    drop table ztest1
    ORA-02449: unique/primary keys in table referenced by foreign keys
    SQL>
    SQL> set pages 0
    SQL> spool c:\windows\temp\drop.sql
    Started spooling to c:\windows\temp\drop.sql
    SQL> select 'DROP TABLE '||TABLE_NAME || ' CASCADE CONSTRAINTS;' from user_tables WHERE table_name like 'ZTEST%';
    DROP TABLE ZTEST1 CASCADE CONSTRAINTS;
    DROP TABLE ZTEST2 CASCADE CONSTRAINTS;
    SQL> spool off
    Stopped spooling to c:\windows\temp\drop.sql
    SQL> @c:\windows\temp\drop.sql
    SQL> DROP TABLE ZTEST1 CASCADE CONSTRAINTS;
    Table dropped
    SQL> DROP TABLE ZTEST2 CASCADE CONSTRAINTS;
    Table dropped
    SQL>

  • JDBC Sender update SQL Statement Question.

    I was wondering if there is a way to have the update SQL statement line in the JDBC sender update by time stamp, this would be very helpful.  Does anyone know a method of doing this?

    In the SAP documentation of the adapter it has this example for using the update SQL statement after the query statement:
    SQL statement for query: SELECT * FROM table WHERE processed = 0;
    SQL statement for update: UPDATE table SET processed = 1 WHERE processed = 0;
    What I want is to be able to put processed = (the current date) instead of processed =1 in the update statement, like this example:
    SQL statement for query: SELECT * FROM table WHERE processed = 0;
    SQL statement for update: UPDATE table SET processed = (the current date) WHERE processed = ' ';
    I seems like you can only use a fixed value for the update statements in the JDBC Sender though, I would like to know if you can use a time stamp or variable there.

  • Setting the sql statement

    http://www.egbolig.dk/drift_bo_syd.rpt (HERE IS THE REPORT)
    We are using SAP Crystal Report .NET Runtime files (http://scn.sap.com/docs/DOC-7824 newest version 13.0.9.1312) in our web asp.net application. Everything have been working fine, but we have can into problems when showing the certain kinda reports.
    In our code get the reports sql statement using getSQLStatement.
    Dim gp As New GroupPath() Dim sql As String = report.ReportClientDocument.RowsetController.GetSQLStatement(gp)
    This will get the sql, and we use this sql (getSqlStatement) and attach a sql WHERE clause from the code to only get a certain number of records.
    The report Drift_bo_syd.rpt has 5 tables, and the following sql statement. 
    Database/Show Sql Statement
    SELECT "rekvstam"."Sel", "rekvstam"."Afd", "rekvstam"."Levadresse", "rekvstam"."Rekvisition", "rekvstam"."Lejemaal", "rekvstam"."Lejer", "rekvstam"."Udfoertaf", "rekvstam"."Udfoertdato", "rekvstam"."Krit", "Selskab"."Adresse", "Selskab"."Postby", "Selskab"."Tlf", "Selskab"."Fax", "rekvstam"."Kontor", "rekvstam"."Hjemme", "rekvstam"."Rekvdato", "rekvstam"."Aftale", "rekvstam"."InitialRet", "rekvstam"."Arbejde", "kreditor"."Att", "rekvstam"."Konto", "Selskab"."Navn", "Selskab"."Email", "Interessentadresse"."Navn", "Interessentadresse"."Adresse", "Interessentadresse"."Postby", "Interessentadresse"."Email1", "Interessentadresse"."Telefon_Fax", "Interessentadresse"."Type", "Interessentadresse"."Tlf1", "rekvstam"."tlfLejer", "kreditor"."Kred", "Interessentadresse"."Interessentnr" FROM  (("Rekvstam" "rekvstam" INNER JOIN "Selskab" "Selskab" ON "rekvstam"."Sel"="Selskab"."Sel") LEFT OUTER JOIN "Kreditor" "kreditor" ON "rekvstam"."Kred"="kreditor"."Kred") INNER JOIN "Interessentadresse" "Interessentadresse" ON "kreditor"."Interessentnr"="Interessentadresse"."Interessentnr" WHERE  "Interessentadresse"."Type"='K' 
    But if we run the report from our asp.net code, we get the following error: 
    Cannot determine the queries necessary to get data for this report. Failed to retrieve data from the database. Error in File Drift_Bo_Syd {97FED382-1BAC-4DB1-970F-9E098ECE28F1}.rpt: Failed to retrieve data from the database.
    After a long time searching for a solution, we found out that if we place the column kred from the kreditor table on the report, the report will work. (field explorer / database fields / kreditor (table) / kred (column)
    Very important is that the field "kreditor.kred" is a primary key of the table kreditor, and also used in the linking.!
    (We can get the report to work if we call the sql statement with the "kreditor"."kred" in the SELECT statement.
    SELECT "kreditor"."kred", "rekvstam"."Sel", "rekvstam"."Afd", "rekvstam"."Levadresse", "rekvstam"."Rekvisition", "rekvstam"."Lejemaal", "rekvstam"."Lejer", "rekvstam"."Udfoertaf", "rekvstam"."Udfoertdato", "rekvstam"."Krit", "Selskab"."Adresse", "Selskab"."Postby", "Selskab"."Tlf", "Selskab"."Fax", "rekvstam"."Kontor", "rekvstam"."Hjemme", "rekvstam"."Rekvdato", "rekvstam"."Aftale", "rekvstam"."InitialRet", "rekvstam"."Arbejde", "kreditor"."Att", "rekvstam"."Konto", "Selskab"."Navn", "Selskab"."Email", "Interessentadresse"."Navn", "Interessentadresse"."Adresse", "Interessentadresse"."Postby", "Interessentadresse"."Email1", "Interessentadresse"."Telefon_Fax", "Interessentadresse"."Type", "Interessentadresse"."Tlf1", "rekvstam"."tlfLejer", "kreditor"."Kred", "Interessentadresse"."Interessentnr" FROM  (("Rekvstam" "rekvstam" INNER JOIN "Selskab" "Selskab" ON "rekvstam"."Sel"="Selskab"."Sel") LEFT OUTER JOIN "Kreditor" "kreditor" ON "rekvstam"."Kred"="kreditor"."Kred") INNER JOIN "Interessentadresse" "Interessentadresse" ON "kreditor"."Interessentnr"="Interessentadresse"."Interessentnr" WHERE  "Interessentadresse"."Type"='K'
    But it should not be necessary to include this field (which is the primary key and used in linking the report) in the sql statement,
    BECAUSE it is not used in the report. So maybe this is a bug?
    It has not been necessary in RDC Crystal Report or RAS Crystal Report in a classic asp envoriment.
    Here is the code we use to set the reports SQL Statement)
    Try
    Dim conn As New SqlConnection(connString)
    conn.Open()
    Dim sd As New SqlDataAdapter(New SqlCommand(nySQL, conn))
    Dim ds As New Data.DataSet()
    Dim navn As String = report.Database.Tables.Item(0).Name
    sd.Fill(ds, navn)
    report.SetDataSource(ds)
    conn.Close()
    Catch ex As Exception
    Throw
    End Try

    Hi Jan
    I understand your problem completely but we have asked  R&D to be able to edit the SQL and they explained due to how the report Engine works it's simply not possible anymore. It would take a complete rewrite in all of our DB drivers and query dll's to be able to allow it. They did that in CR 9 when they rewrote the DB drivers and removed the SQL part of the code into separate dll's and that is when the ability was removed, it's been that way ever since.
    One possibility is to get the SQL from the Report and then connect to your DB using a .NET and if the results from the SQL is less than 5K rows and not too many columns you could then set the Report data source to a Dataset.
    As long as all of the field names are the same CR will run the report using this work flow.
    For data larger than 5K rows, limit is due to memory resources, you could save the DS to an XML file and then set the reports data source to the XML file. We've seen 100meg XML's used so the amount of data should not be a problem, but of course there are limits to everything so test...
    This should not affect performance much.
    So the work flow would be:
    Load the report
    Get the SQL Statement
    Paste it into a Dataset Query
    Something like this should get you started:
    //string connString = "Provider=SQLOLEDB;Data Source=MySQLServer;Database=xtreme;User ID=sa;Password=pw";
    string connString = "Provider=SQLNCLI10;Server=MySQLServer;Database=xtreme;User ID=sa;Password=pw";
    Detail"".""Quantity"" FROM   ""xtreme"".""dbo"".""Orders Detail"" ""Orders Detail""";
    string sqlString = @"SELECT top 10*  FROM  ""xtreme"".""dbo"".""Financials"" ""Financials""";
    System.Data.OleDb.OleDbConnection oleConn = new System.Data.OleDb.OleDbConnection(connString);
    System.Data.OleDb.OleDbCommand cmd = oleConn.CreateCommand();
    cmd.CommandText = sqlString;
    System.Data.DataSet ds = new System.Data.DataSet();
    OleDbDataAdapter oleAdapter = new OleDbDataAdapter(sqlString, oleConn);
    //OleDbDataAdapter oleAdapter2 = new OleDbDataAdapter(sqlString2, oleConn);
    DataTable dt1 = new DataTable("Financials");
    //DataTable dt2 = new DataTable("Orders Detail");
    oleAdapter.Fill(dt1);
    //oleAdapter2.Fill(dt2);
    ds.Tables.Add(dt1);
    //ds.Tables.Add(dt2);
    ds.WriteXml("c:\\reports\\sc2.xml", XmlWriteMode.WriteSchema);
    // as long as the field names match exactly Cr has no problems setting report to a DS.
    try
        rpt.SetDataSource(ds.Tables[0]); // incremtent [0] for more than 1 table.
        rpt.SetDataSource(ds);
    catch (Exception ex)
        MessageBox.Show("ERROR: Schema Mismatch. Error reported by CR: " + ex.Message);
    //Now check for subreport and set to same DS
    foreach (CrystalDecisions.CrystalReports.Engine.Section section in rpt.ReportDefinition.Sections)
        foreach (CrystalDecisions.CrystalReports.Engine.ReportObject reportObject in section.ReportObjects)
            if (reportObject.Kind == ReportObjectKind.SubreportObject)
                CrystalDecisions.CrystalReports.Engine.SubreportObject subReport = (CrystalDecisions.CrystalReports.Engine.SubreportObject)reportObject;
                CrystalDecisions.CrystalReports.Engine.ReportDocument subDocument = subReport.OpenSubreport(subReport.SubreportName);
                subDocument.SetDataSource(ds);
    And for XML it would use this part, not above I am saving the data and structure in the XML file so it should match what is in the report:
    foreach (CrystalDecisions.CrystalReports.Engine.Table rptTable in rpt.Database.Tables)
        try
            rptTable.Location = btrDataFile.ToString(); // @"D:\Atest\" + rptTable.Location + ".xml";
        catch (Exception ex)
            MessageBox.Show("ERROR: " + ex.Message);
    Only issue you may run into is sometimes XML does not have a direct field type and your original data source but you'll get an error if that happens which could be trapped and handled.
    If you have a report that only uses 2 tables I do have code that will convert it to use a Command Object. That is the limit the engine is capable of, there is a lot of logic to be able to do this in CRD and the SDK so that is all we could get for now.
    I hope that helps
    Don

  • Dynamic select sql statement

    Hi currently i have a problem with the sql statement.
    The field name and the table name of the sql statement will depend on what the user input. We need to find out what records is in tableA columnA and not in tableB columnB.
    Below is my sql statement:
    SELECT * FROM (TABLEA) INTO TABLE ITABA
    WHERE (COLUMNA)
    NOT IN ( SELECT (COLUMNB) FROM (TABLEB) ).
    =============================================
    ColumnA = "the user input the field name"
    TableA = " the user input the table name"
    TableB = " the user input the table name"
    The problem lies at the WHERE clause. The system generate a sql error which says "unable to find the field name".

    Hi,
    Check the following code:
    For dynamic table name....
    REPORT demo_select_dynamic_database .
    DATA wa TYPE scarr.
    DATA name(10) TYPE c VALUE 'SCARR'.
    SELECT *
    INTO wa
    FROM (name) CLIENT SPECIFIED
    WHERE mandt = '000'.
    WRITE: / wa-carrid, wa-carrname.
    ENDSELECT.
    For dynamic field list
    REPORT demo_select_dynamic_columns .
    DATA: itab TYPE STANDARD TABLE OF spfli,
                wa LIKE LINE OF itab.
    DATA: line(72) TYPE c,
    list LIKE TABLE OF line(72).
    line = ' CITYFROM CITYTO '.
    APPEND line TO list.
    SELECT DISTINCT (list)
    INTO CORRESPONDING FIELDS OF TABLE itab
    FROM spfli.
    IF sy-subrc EQ 0.
    LOOP AT itab INTO wa.
    WRITE: / wa-cityfrom, wa-cityto.
    ENDLOOP.
    ENDIF.
    Regards,
    Bhaskar

  • Dropping tables in a specified user where in i dont know the SYS privilege

    Hi,
    I have 10 users with each user containing about 120 tables, but i want to drop all the tables without dropping the users and im working on a testing database where in i only have access to ALL_USERS...
    Can anyone help me in this regard......
    Thanks
    - Sri

    Ok, I'll try to be clearer.
    in SQL*Plus, first enter the line:
    sql> spool drop_tables.sql;
    then enter the query as above. This should output a load of lines which read 'drop table owner.table_name; and the last line will be row count.
    Then issue the command:
    sql> spool off;
    you should then see that a file has been created on your filesystem called drop_tables.sql. Take a look inside and it will contain lots of 'drop table' commands.
    return to SQL*Plus and run that script:
    mysql> @drop_tables.sql
    when you are SURE that you are happy with what has been dropped, issue the COMMIT;
    if you are not happy, issue a ROLLBACKl
    regards
    James

  • SQL statement not executing

    Please enlighten me. This is driving me crazy.
    I don't know if this is a database or java code related problem.
    JVM: 1.4.2
    Database: Oracle 9i
    Objective: trying to add a row into a table
    Problem: 1. SQL statement never gets executed.
    2. Application freezes. I have to terminate it myself.
    Any Ideas?
    void addCourse(){
    try {
        DriverManager.registerDriver ( new oracle.jdbc.driver.OracleDriver () ) ;
       System.out.println("Driver registered");  //---> ok.
    Connection conn = DriverManager.getConnection ( dbPath, username, password ) ;
       System.out.println("Connected");   // -----> it connects fine
       ResultSet rset = stmt.getResultSet();
       System.out.println("getting result set");  //-----> gets the resultSet fine
      Statement stmt = conn.createStatement();
      System.out.println("statement created");  //------> it creates statement
    7 = are the credits. Number on table. Length allowed 5.
    CS 500 = are the course code. Varchar2 on table. Length allowed 20
    Java = Actual course name. Varchar2 on table. Length 30
    3 = credits. Number on table. Length 5.
              // Prepare a statement to insert a record
              String sql = "INSERT INTO course VALUES (7 , 'CS 500', 'Java', 3 )"; //-->ok. Tested it manually 
              // Execute the insert statement
            stmt.executeUpdate(sql);  //----> *** java program freezes right here.***
            System.out.println("sql executed");   //--> Checked table. SQL never gets executed.
    catch ( SQLException ex ) {   //---> no error messages thrown.
    System.err.println(ex.getMessage());
      System.err.println(ex.getErrorCode());
      System.err.println(ex.getSQLState());
    }

    Nothing looks amiss in the code... How long are you waiting before you manually terminate?
    Can you replace the executeUpdate() with execute and change the INSERT to a SELECT? Does that work normally (you should be sure to get at least one row to verify that it is working correctly)? Can you select and update a different table in a different tablespace successfully?
    Couple of possibilities (I know this is weak):
    1) You have hit a deadlock condition because the table is locked by another or same process.
    2) You are running into network problems.
    3) Your insert is being queued up in Oracle's transaction manager (if configured).
    4) Have you tried both the Oracle thin and Oracle OCI driver? Do they both fail without error?
    5) Can you turn off autoupdate and try the insert? Does the executeUpdate() return then?

  • How can I write a SQL statement which checks if a table exists?

    How can I write a SQL statement which tells me whether a table exists?

    execute an sql query: select * from <tablename>
    catch the exception n check whether the erroe code
    matches the one that occurs for table doesn't exist
    that's itHow is your answer any different from the one given in the first reply?
    It isn't.
    As WorkForFood says DatabaseMetaData has a bunch of methods for getting information about tables but this is more useful when you don't know the names of any of the tables.. it sounds like you do so I would concur SELECT from table is probably the quickest way to go. If it helps the Xopen error should be either S1000 or 42S01 (I think) but I would try and see if there is a specific vendor code for table not found/not exists error and check for that.

  • Drop table is not Working in SQL

    Hi,
    I am trying to drop table in below code in dynamic way, but facing error. 
    Looking for your support.
    /**********************************RESET************************/
    if @TypeOfUpdate='Reset'
    Begin
    Drop table [' + @DestinationTable + ']  
    exec('select * into [' + @DestinationTable + '] from openrowset(''Microsoft.ACE.OLEDB.12.0'', ''Excel 12.0;HDR=YES;Database=' + @TABLENAME + ''', ' + ''' select * from '+@SourceSheet + ''')')
    PRINT 'Congratulations!!!! Database is Reset.';
    END
    above is part of SP code where I am getting an error if i run the below code. 
    EXEC [ImportExcelFile_Reset] 'C:\temp\TestFiles\OPENASNs.xlsx','Sheet1', 'test', 'Reset'
    ------------Error-------
    (1 row(s) affected)
    Msg 3701, Level 11, State 5, Procedure ImportExcelFile_Reset, Line 53
    Cannot drop the table '' + @DestinationTable + '', because it does not exist or you do not have permission.
    Msg 2714, Level 16, State 6, Line 1
    There is already an object named 'test' in the database.
    SharePoint_Consultant_EMEA

    You you need a dynamic SQL statement for drop too. :)
    if @TypeOfUpdate='Reset'
    Begin
    exec('Drop table '+ @DestinationTable+';
    select * into [' + @DestinationTable + ']
    from openrowset(''Microsoft.ACE.OLEDB.12.0'', ''Excel 12.0;HDR=YES;Database=' +
    @TABLENAME + ''', ' + ''' select * from '+@SourceSheet + ''')')
    PRINT 'Congratulations!!!! Database is Reset.';.......
    Satheesh
    My Blog | How to ask questions in technical forum

Maybe you are looking for

  • FM 'JOB_CLOSE' error ,  JOB_NOSTEPS, user authorization

    There are two users,  userA and userB when i log in as userA to submit job as user B, it was working fine. if the program run by userA:    submit XXXXX       WITH xxxx           to sap-spool           destination 'LOCL'           list name  'FINL_INV

  • Acrobat PDF Printer don´t work

    When I choose File->Print->"Adobe PDF Printer" from any application (i.E. "Ai") I get following two windows. The first Window will disappear with 100%, but the second don´t and no file will be created?!!??!??!? My system: Win7 64 and Adobe CC (Acroba

  • [Resolved] Compaq n620c video problems

    got i686 to install on this laptop with no problem... attempted to use ati FOSS drivers for video, got error that it didn't recognize the driver (will post exact error tomorrow if I can get internet where the laptop is, else I'll copy the error and p

  • Acrobat Pro DC, now Chrome doesn't work.

    Installed the new Acrobat Pro DC, now Chrome doesn't work, Acrobat won't work either.  What to do?

  • Tips on how to handle situation where client won't pay invoice?

    Hello, We usually request that clients fill out a Direct debit form before going live with their site.  However on a one off occasion, our client was desperate and promised to provide us with the DD before next billing period.  It turns out they have