Using a parameter for a table name?

In SQL Server, can you use a parameter for a table name?  I'm working with Visual C# and want to do something like this:
SELECT MAX(ItemID) FROM @TableName;
Can this be done?
(Basically, I have three separate methods within a class--one for each table I have; and each one will perform the above query but on different table names.  I'd like to see if there is a way that I can have just one method that will allow me to specify
the table name.)

As pointed out in other posts, you can. But a more relevant question is whether you should.
A table in a relational database is supposed to model a unique entity, and each column in the table is supposed to model a unique attribute. This is not always how it is, but it is from this model a relational database is designed.
From this angle, having a dynamic table name does not really make sense for application code. (Administrative actions is a different story.) Think of it this way: have you ever wanted to make the class name dynamic in C#?
Admittedly, it is different in .NET, because everything inherits from System.Object, but in a relational database there is no inheritence.
Anyway, if you are using stored procedures, you should have one stored procedure per table. Physically, in the plan cache, there will be one query plan per table, no matter how you do it.
If you are submitting SQL statements from your application, it is a different matter. In this case, I find it difficult to object if you have a class that performs generic actions against tables. Then you build the SQL string in the client code.
However, no matter how you do it, you need to be careful to avoid SQL injection. We had the example:
DECLARE @TableName nvarchar(50),@sqlCommand nvarchar(max)
  SET @TableName = ' ItemInformation'
  SET @sqlCommand = 'SELECT MAX(ItemID) FROM ' + @TableName
EXEC (@sqlCommand)
But what if we have:
  SET @TableName = ' sys.objects; SHUTDOWN WITH NOWAIT; --'
As long as we do it in T-SQL, we can (and we should do!) this to prevent SQL injection:
  SET @sqlCommand = 'SELECT MAX(ItemID) FROM ' + quotename(@TableName)
If you build your SQL strings in C#, you will need to employ other checks. There is only an issue if the user can inject data somewhere, but your generic class will not have knowledge of this, and must assume the worst.
Erland Sommarskog, SQL Server MVP, [email protected]

Similar Messages

  • How to look for the Table Name

    Hi Friends,
    Sometimes we need to download the table for the desired information if the same is not available from a particular report. How to look for the table name? Is there a report or a particular feild, where we can find the name of the particular table?
    Thanks for the assistance.
    Regards

    Hi Friend,
    If you want to see the structures then go to SE11. Sometimes it happens that you cannot find the table names but only fields. In such case, if you want to find the Table names which is not available, then go to SE90.
    Abap Dictionary > Fields > Table Fields.
    Now Enter the Field name in Right Hand Side of the screen then Execute. You will see the all tables by which that Fields are used.
    Regards,
    Jigar

  • Building a data flow task, within a foreach loop for dynamic table name, but ole db source not allowing variable

    In my control flow, I set up a variable for the table name, enumerated by SMO, following the instructions from the link here:
    http://www.bidn.com/blogs/mikedavis/ssis/156/using-a-for-each-loop-on-tables-ssis
    Now, I put a data flow task inside the foreach. I selected the OLE DB connection manger for my database, set the Data access mode to "Table name or view name variable", and selected my variable name from the drop down. So far so good. When I click on OK,
    it gives me an error 0x80040E37, basically saying it can't open the rowset for "my variable", Check that the object exists in the database.
    So, I assume I won't be able to do this "that' easily, and I will need to build a "SQL command from variable" or some such thing. Any advice on how to build this Source editor to dynamically name my columns from the variable?
    Thanks in advance!
    mpleaf

    Hi mpleaf,
    Please try to set "ValidateExternalData" to False in your OLE DB Source Properties and "DelayValidation" property to TRUE, please refer to similar threads:
    http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/620557d9-41bc-4a40-86d5-0a8d2f910d8c/
    http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/456f2201-447c-41b3-bf27-b3ba47e6b737
    Thanks,
    Eileen
    Eileen Zhao
    TechNet Community Support

  • How to increase the max character for a table name..!!

    Hi All,
    The maximum characters that supports for the table Name is 30
    How can I increase this so that I can have table names lengthier than 30
    This is required as I was doing a conversion of the database from SQL server 2005 to Oracle 9i
    Many thanks in advance...
    Best Regards..,

    So How can I make it possible..?!!If it not possible, you cannot make it possible.
    If you can create a synonym on more than 30 char., you cannot use it on more than 30 char :
    SQL> create synonym my_very_long_synonym_name_for_emp_table for emp;
    Synonym created.
    SQL> select count(*) from my_very_long_synonym_name_for_emp_table;
    select count(*) from my_very_long_synonym_name_for_emp_table
    ERROR at line 1:
    ORA-00972: identifier is too long
    SQL> select * from user_synonyms;
    SYNONYM_NAME                   TABLE_OWNER                    TABLE_NAME
    DB_LINK
    /91b591a7_MY_VERY_LONG_SYNONYM SCOTT                          EMP
    SQL> select count(*) from "/91b591a7_MY_VERY_LONG_SYNONYM";
      COUNT(*)
            14Nicolas.

  • How to use remote directory for external table

    Hi Folks,
    I have 2 Oracle 11GR2 64 bit database installed on Win 2008 server as prod1 and prod2.
    I have one directory created on prod1 server as EXT_TAB_DIR using the path as D:\OrsDWtest_dir .
    I want to use this directory in Prod2 server and use external table using this remote directory.
    I am able to access the Prod1 directory from Prod2 machine and also i have created Network map drive as Z drive pointing to that prod1 D:\OrsDWtest_dir directory. Also i checked read and Write permissions are there . I am able to create the external table but when i try to fetch the data i m getting below error ..
    ORA-29913: error in executing ODCIEXTTABLEOPEN callout
    ORA-29400: data cartridge error
    KUP-04040: file IOMM_20121213_060736.csv in EXT_TAB_DIR not found
    now my doubt is this possible ? Can we use remote directory for External table ? or is there is there any alternative way to achieve same ?
    Thanks & Regards,
    Vikash Jain(DBA)

    could you confirm the name and the existence of this file "IOMM_20121213_060736.csv" ?
    same error like:
    http://www.oracle-base.com/articles/9i/external-tables-9i.php
    if the load files have not been saved in the appropriate directory the following result will be displayed.
    SQL> SELECT *
      2  FROM   countries_ext
      3  ORDER BY country_name;
    SELECT *
    ERROR at line 1:
    ORA-29913: error in executing ODCIEXTTABLEOPEN callout
    ORA-29400: data cartridge error
    KUP-04040: file Countries1.txt in EXT_TABLES not found
    ORA-06512: at "SYS.ORACLE_LOADER", line 14
    ORA-06512: at line 1Edited by: Fran on 10-ene-2013 23:32

  • ABAP for Super Dumps: Import- & Export-Parameter for a Table in a FM

    Hello ABAP Profs,
    sorry I am BW.
    <b>Import- & Export-Parameter for a Table in and out of an Function Modul.</b>
    I want to import a table into a Function Module, change it and export it again.
    How do I have to define the Import- and Export- Parameters in the FM ?
    The table looks looks this:
    DATA: zvpshub_tab TYPE SORTED TABLE OF /bic/pzvpshub WITH UNIQUE KEY
    /bic/zvpshub objvers /bic/zvpsoursy INITIAL SIZE 0.
    Thanks a lot
    Martin Sautter

    Hi Clemens,
    <u>in SE11</u> I defined a datatype of Type Structure: ZVPSHUB_ROW.
    <u>in SE11</u> I defiend a datatype of Type Tabletype: ZVPSHUB_TAB,
    bases on Rowtype ZVPSHUB_ROW.
    <u>in SE 80</u> I creates an FM with a CHANGEING Parameter referencing ZVPSHUB_TAB:
    FUNCTION ZVP_SHUB_TAB_LOAD.
    ""Lokale Schnittstelle:
    *"  CHANGING
    *"     VALUE(SHUB_TAB) TYPE  ZVPSHUB_TAB
    <u>in RSA1</u> in BW in the Startroutine of the Upload Rules in defined the table:
    DATA:shub_tab          TYPE zvpshub_tab.
    <u>in RSA1</u> in BW in the Startroutine of the Upload Rules in defined the table:
    DATA:shub_tab          TYPE zvpshub_tab.
    <u>in RSA1</u> in BW in the Startroutine i called the FM
    CALL FUNCTION 'ZVP_SHUB_TAB_LOAD'
        CHANGING
          shub_tab = shub_tab.
    and it works ..
    Thank You
    Martin Sautter

  • Configuring profile parameter for a table lock object

    Hi Experts-
      I want to set the 'wait time' (_WAIT) parameter as a profile parameter for a table lock object.
      I have created a lock object on a ZTable. I lock and unlock this object in exclusive non-cumulative mode through the enqueue and dequeue lock object function modules. These generated FMs are invoked via my custom function module.
      My function module will run in the background as a scheduled task in R/3. I execute the Enqueue FM at the start of the FM and keep the table locked until the last step finishes in my FM and then I Dequeue it. I want to have the processing wait and retry the Enqueuring FM at set intervals in case the one run doesn't finish entirely and a new run of this same job kicks off.
    Thank you,
    - Vik.

    Set the wait parameter = 'X'.  These means that if it encounters a lock, then it will wait a certain time for the lock to be released.  This certain time is a system value set by your basis team.  I don't imagine it being a very long time.
      CALL FUNCTION 'ENQUEUE_EZPIPHYINVREF'
           EXPORTING
                MODE_ZPIPHYINVREF = 'E'
                MANDT             = SY-MANDT
                _WAIT             = 'X'.
    Regards,
    Rich Heilman

  • How to use dynamic query for Result table

    Hello Experts,
    I want to use dynamic query and then display the result in the assignment block.
    Using dynamic query BTQAct and BTQRAct and base on some search criteria i want tofilter and then append the result in the result table of that custom context node, and then it should display the result in the view in UI.
    SO can you please provide me the samplle code on how to use the dynamic query and append in the result table.
    Regards.

    Hi,
    Please find below sample code:
    data:  query         TYPE REF TO cl_crm_bol_dquery_service,
               result        TYPE REF TO if_bol_bo_col.
    DATA: lt_params       TYPE crmt_name_value_pair_tab,        
               lwa_params      TYPE crmt_name_value_pair.             
    query = cl_crm_bol_dquery_service=>get_instance( 'BTQAct' ). " Get instance of dynamic query
    Set general query parameter for maximum number of hits
          lwa_params-name = 'MAX_HITS' .
          lwa_params-value = '50'.
          APPEND lwa_params TO lt_params.
          query->set_query_parameters( it_parameters = lt_params ).
          query->add_selection_param( iv_attr_name = 'OBJECT_ID'
                                                    iv_sign      = 'I'
                                                    iv_option    = 'EQ'
                                                    iv_low       = <lv_objectid>
                                                    iv_high      = '' ). " Set your search criteria. Repeat this code if you have multiple parameters
    "You can find possible search options for a query object in  GENIL_BOL_BROWSER
    result ?= query->get_query_result(  ).   " Get result from your search query
    me->typed_context-> <your result context node>->set_collection( result ). 
    Here you will have to create a context node in your view which would refer to query result object like for BTQAct its BTQRAct                      
    Hope this helps.
    e Regards,
    Bhushan

  • How to put parameter for object/table ID in BW Web Report

    Hi All,
    In my BW Web report, i want to get my object TABLE_1 but the code below seems not to work.
    var mytable = document.getElementsByTagName("table");
    Checking on it, i think IE recognize only document.getElementsByID. ( I tested it by manually creating a table in my template and putting a tag for table ID) But BW does not generate the Object ID in the parameters below, only the name.
             <param name="OWNER" value="SAP_BW"/>
             <param name="CMD" value="GET_ITEM"/>
             <param name="NAME" value="TABLE_1"/>
             <param name="ITEM_CLASS" value="CL_RSR_WWW_ITEM_GRID"/>
             <param name="DATA_PROVIDER" value="DATAPROVIDER_1"/>
             <param name="GENERATE_CAPTION" value=""/>
             <param name="CAPTION" value="jezel"/>
             <param name="ONLY_HIERARCHY_NAVIGATION" value="X"/>
             <param name="BLOCK_SIZE" value="0"/>
             <param name="SHOW_PAGING_AREA_BOTTOM" value=""/>
             ITEM:            TABLE_1
    do you know how i can add a parameter for object ID? do you know any steps how i can retrieve my table using javascript?
    Thanks in advance.

    Hi JTi,
    what i have understood from your requirement is that you want to access the web item table_1 in javascript, you can get that as below:
    Add
    <span> 
    tag before your web item and set its id to table.
    <span id = "table">
    <param name="OWNER" value="SAP_BW"/>
    <param name="CMD" value="GET_ITEM"/>
    <param name="NAME" value="TABLE_1"/>
    <param name="ITEM_CLASS" value="CL_RSR_WWW_ITEM_GRID"/>
    <param name="DATA_PROVIDER" value="DATAPROVIDER_1"/>
    <param name="GENERATE_CAPTION" value=""/>
    <param name="CAPTION" value="jezel"/>
    <param name="ONLY_HIERARCHY_NAVIGATION" value="X"/>
    <param name="BLOCK_SIZE" value="0"/>
    <param name="SHOW_PAGING_AREA_BOTTOM" value=""/>
    ITEM: TABLE_1
    </span>
    In javascript access it as :
    var mytable = document.getElementsById("table");
    Hope this helps
    Thanks
    Dipika

  • Using user parameter for

    Hello,
    I have created a report using an xml pds. I am using a servlet for the xml data stream source. Everything works great with the url to the servlet hard-coded between the <xml></xml> tags (ex. <xml>http://10.3.35.119:9004/ssapp/servlet/ScheduleDataServlet</xml>) but when I try using a user parameter between the tags (so I will be able to dynamically change the url to this servlet) it bombs. Please see my source code and error message below. Any help would be greatly appreciated, I've been stuck on this for days! Thanks!
    <rw:report id="recoveryCenterScheduleReport" parameters="server=myreportserver&userid=ssstage/ssstage@DEVL&p_xmlDataURL=http://10.3.35.119:9004/ssapp/servlet/ScheduleDataServlet">
    <rw:objects id="objects">
    <?xml version="1.0" encoding="WINDOWS-1252" ?>
    <report name="XMLscheduleReport" DTDVersion="9.0.2.0.0">
    <xmlSettings xmlTag="XMLSCHEDULEREPORT" xmlPrologType="text">
    <![CDATA[<?xml version="1.0" encoding="&Encoding"?>]]>
    </xmlSettings>
    <data>
    <userParameter name="XML_HTTPS" datatype="character"
    pluginClass="oracle.reports.plugin.datasource.xmlpds.XMLDataSourceFactory"
    width="255" defaultWidth="0" defaultHeight="0" display="no"/>
    <userParameter name="p_xmlDataURL" datatype="character" width="100"
    precision="10" defaultWidth="0" defaultHeight="0"/>
    <dataSource name="QP_1">
    <plugin
    factoryClass="oracle.reports.plugin.datasource.xmlpds.XMLDataSourceFactory"
    majorVersionNumber="1" minorVersionNumber="2"
    signOnParameter="XML_HTTPS">
    <![CDATA[<xmlpds DTDVersion=" 1.0">
    <dtd>null</dtd>
    <schema>file:///C:/Practic Workspace/Practice/WEB-INF/xsd/scheduleReport.xsd</schema>
    <XSQLschema>null</XSQLschema>
    <XSQLWithDTD>false</XSQLWithDTD>
    <type>false</type>
    <xmlWritten>true</xmlWritten>
    <validate>true</validate>
    <xml>&<[b]p_xmlDataURL></xml>
    <xsl>null</xsl>
    javax.servlet.jsp.JspException: rwlib-1: REP-0002: Unable to retrieve a string from the report builder message file.
    REP-0069: Internal error
    XMLPDS-63004:Generic error while parsing the URL stream name instead of <.
    REP-4111: Fail to create pluggable data source 'QP_1'
         at oracle.reports.jsp.ObjectsTag.doEndTag(ObjectsTag.java:180)
         at jsp.reports._schedule._XMLscheduleReport._jspService(_XMLscheduleReport.java:87)
    ....

    Never mind, I discovered the problem. I wasn't using the necessary xml escape characters for the user parameter embedded in the xml.

  • CTAS using dbms_metadata.get_ddl for Partitioned table

    Hi,
    I would like to create a temporary table from a partitioned table using CTAS. I plan to use the following steps in a PL/SQL procedure:
    1. Use dbms_metadata.get_ddl to get the script
    2. Use raplace function to change the tablename to temptable
    3. execute the script to get the temp table created.
    SQL> create or replace procedure p1 as
    2 l_clob clob;
    3 str long;
    4 begin
    5 SELECT dbms_metadata.get_ddl('TABLE', 'FACT_TABLE','USER1') into l_clob FROM DUAL;
    6 dbms_output.put_line('CLOB Length:'||dbms_lob.getlength(l_clob));
    7 str:=dbms_lob.substr(l_clob,dbms_lob.getlength(l_clob),1);
    8 dbms_output.put_line('DDL:'||str);
    9 end;
    12 /
    Procedure created.
    SQL> exec p1;
    CLOB Length:73376
    DDL:
    PL/SQL procedure successfully completed.
    I cannot see the DDL at all. Please help.

    Thanks Adam. The following piece of code is supposed to do that. But, its failing because the dbms_lob.substr(l_clob,4000,4000*v_intIdx +1); is putting newline and therefore dbms_sql.parse
    is failing.
    Please advice.
    create table my_metadata(stmt_no number, ddl_stmt clob);
    CREATE OR REPLACE package USER1.genTempTable is
    procedure getDDL;
    procedure createTempTab;
    end;
    CREATE OR REPLACE package body USER1.genTempTable is
    procedure getDDL as
    Description: get a DDL from a partitioned table and change the table name
    Reference: Q: How Could I Format The Output From Dbms_metadata.Get_ddl Utility? [ID 394143.1]
    l_clob clob := empty_clob();
    str long;
    l_dummy varchar2(25);
    dbms_lob does not have any replace function; the following function is a trick to do that
    procedure lob_replace( p_lob in out clob, p_what in varchar2, p_with in varchar2 )as
    n number;
    begin
    n := dbms_lob.instr( p_lob, p_what );
    if ( nvl(n,0) > 0 )
    then
    dbms_lob.copy( p_lob,
    p_lob,
    dbms_lob.getlength(p_lob),
    n+length(p_with),
    n+length(p_what) );
    dbms_lob.write( p_lob, length(p_with), n, p_with );
    if ( length(p_what) > length(p_with) )
    then
    dbms_lob.trim( p_lob,
    dbms_lob.getlength(p_lob)-(length(p_what)-length(p_with)) );
    end if;
    end if;
    end lob_replace;
    begin
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'STORAGE',false);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'SEGMENT_ATTRIBUTES',false);
    DBMS_METADATA.SET_TRANSFORM_PARAM (DBMS_METADATA.SESSION_TRANSFORM,'SQLTERMINATOR',true);
    DBMS_METADATA.SET_TRANSFORM_PARAM (DBMS_METADATA.SESSION_TRANSFORM,'SEGMENT_ATTRIBUTES',false);
    execute immediate 'truncate table my_metadata';
    -- Get DDL
    SELECT dbms_metadata.get_ddl('TABLE', 'FACT','USER1') into l_clob FROM DUAL;
    -- Insert the DDL into the metadata table
    insert into my_metadata values(1,l_clob);
    commit;
    -- Change the table name into a temporary table
    select ddl_stmt into l_clob from my_metadata where stmt_no =1 for update;
    lob_replace(l_clob,'"FACT"','"FACT_T"');
    insert into my_metadata values(2,l_clob);
    commit;
    -- execute immediate l_clob; <---- Cannot be executed in 10.2.0.5; supported in 11gR2
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'DEFAULT');
    end getDDL;
    Procedure to create temporary table
    procedure createTempTab as
    v_intCur pls_integer;
    v_intIdx pls_integer;
    v_intNumRows pls_integer;
    v_vcStmt dbms_sql.varchar2a;
    l_clob clob := empty_clob();
    l_str varchar2(4000);
    l_length number;
    l_loops number;
    begin
    select ddl_stmt into l_clob from my_metadata where stmt_no=2;
    l_length := dbms_lob.getlength(l_clob);
    l_loops := ceil(l_length/4000);
    for v_intIdx in 0..l_loops loop
    l_str:=dbms_lob.substr(l_clob,4000,4000*v_intIdx +1);
    l_str := replace(l_str,chr(10),'');
    l_str := replace(l_str,chr(13),'');
    l_str := replace(l_str,chr(9),'');
    v_vcStmt(v_intIdx) := l_str;
    end loop;
    for v_intIdx in 0..l_loops loop
    dbms_output.put_line(v_vcStmt(v_intIdx));
    end loop;
    v_intCur := dbms_sql.open_cursor;
    dbms_sql.parse(
    c => v_intCur,
    statement => v_vcStmt,
    lb => 0,
    --ub => v_intIdx,
    ub => l_loops,
    lfflg => true,
    language_flag => dbms_sql.native);
    v_intNumRows := dbms_sql.execute(v_intCur);
    dbms_sql.close_cursor(v_intCur);
    end createTempTab;
    end;
    /

  • Use of quotes in a table name?

    Hello,
    It seems Oracle treats a table name with and without quotes differently.
    SQL> create table abc (x integer);
    SQL> create table "abc" (y integer);
    These two commands result in two different tables as can be seen from the following commands:
    SQL> desc abc;
    SQL> desc "abc";
    However, I cannot get the list of tables.
    SQL> select * from tab where tname like '%abc%';
    returns just one row.
    SQL> select * from all_objects where object_name like '%abc%' also does not show me abc and "abc" as two separate tables.
    Q1. Is there a way to obtain the proper list?
    Q2. What is the proper qualifier for specifing a table name? For example, SQL Server supports "[" and "]" around the table name. However, I could not find the equivalent grammar for PL/SQL.
    The following command works (by trial and error):
    SQL> select * from (abc);
    However, the following doesn't:
    SQL> drop table (abc);
    which means that "(" and ")" are not the qualifiers.
    Thank you in advance for your help.
    Pradeep

    Import and export and the other tools use quotes so
    that objects will be properly re-created as they were
    originally specified, even if some one uses reserved
    words or case sensitive names. At least they should. I recently had a customer using FoxPro (!) to access my Oracle Datawarehouse and he named one of his column "ALTER" (age in german). Then he complained that my database is not working because he was getting an Oracle error (ORA-00936: missing expression)!
    However, if some developer made me
    type:
    SELECT "MyCol1", "MyCol2", ...
    FROM "HisTable"
    WHERE "SomeStrangeColumnName" = 42every time,
    I would think seriously of homocide :-).I know the feeling :-)

  • Parameterized cursor for varient Table name?

    Hi all,
    I am using Oracle 9i and have a cursor defined as :-
    Code:
    CREATE PROCEDURE Proc_Abc
    AS
    CURSOR
    My_Cursor (UserName VARCHAR) IS
    SELECT Emp_Name, Salary FROM Employee_Table
    WHERE User_Name = UserName;     
    (Rest of the code)
    This code is working perfectly, but if I try to provide the table name through the cursor variable, it gives an error
    Below is the code that I am writing to pass table name through variable:-
    Code:
    CREATE PROCEDURE Proc_Abc
    AS
    CURSOR
    My_Cursor (TableName VARCHAR, UserName VARCHAR) IS
    SELECT Emp_Name, Salary FROM TableName
    WHERE User_Name = UserName;     
    (Rest of the code)
    All the tables that I need to pass through cursor variables have the same fields and are all pre known to me, thats why "SELECT Emp_Name, Salary " is remaining common throughout.
    Please suggest how can I make a cursor with variant tables?
    Thanks in advance.

    The following procedure compares between two tables and then it picking the column from all_tab_column table and finally execute the SELECT statement to compare the data between this two table. But, you can proceed your program taking help from this -
    satyaki>ed
    Wrote file afiedt.buf
      1  create or replace procedure compr_tab_dat(TAR_TAB IN VARCHAR2,
      2                                            TAR_UID IN VARCHAR2,
      3                                            SRC_TAB IN VARCHAR2,
      4                                            SRC_UID IN VARCHAR2)
      5  is
      6   cursor c1
      7   is
      8    select column_name
      9    from (
    10           select column_name,column_id
    11           from all_tab_columns
    12           where table_name = SRC_TAB
    13           and   owner = SRC_UID
    14           intersect
    15           select column_name,column_id
    16           from all_tab_columns
    17           where table_name = TAR_TAB
    18           and   owner = TAR_UID
    19         )
    20     order by column_id;
    21   cursor c_count
    22   is
    23     select count(column_name) as c_cnt
    24     from (
    25             select column_name
    26             from all_tab_columns
    27             where table_name = SRC_TAB
    28             and   owner = SRC_UID
    29             intersect
    30             select column_name
    31             from all_tab_columns
    32             where table_name = TAR_TAB
    33             and   owner = TAR_UID
    34           );
    35   rec1 c1%rowtype;
    36   rec2 c1%rowtype;
    37   rec3 c1%rowtype;
    38   rec6 c_count%rowtype;
    39   cnt  number(10);
    40   cnt1  number(10);
    41   str  varchar2(32000);
    42   --str  clob;
    43  BEGIN
    44     cnt := 0;
    45     cnt1 := 1;
    46     dbms_output.enable(10000000);
    47     for rec6 in c_count
    48     loop
    49      cnt := rec6.c_cnt;
    50     end loop;
    51     if cnt = 0 then
    52        dbms_output.put_line('No matched columns found.... ');
    53     else
    54        dbms_output.put_line('UnMatched Datas Are-- ');
    55           str:='declare '||
    56          '  cursor c3 '||
    57          '  is '||
    58          '    select ';
    59           open c1;
    60           loop
    61             fetch c1 into rec1;
    62             exit when c1%notfound;
    63             if cnt = cnt1 then
    64                str:= str||rec1.column_name;
    65             elsif cnt1<cnt then
    66               str:= str||rec1.column_name||',';
    67             end if;
    68             cnt1 := cnt1 + 1;
    69           end loop;
    70           close c1;
    71           str:=str||' from '||SRC_TAB||
    72                ' minus '||
    73                ' select ';
    74           cnt1:=1;
    75           open c1;
    76           loop
    77             fetch c1 into rec2;
    78             exit when c1%notfound;
    79             if cnt = cnt1 then
    80                str:= str||rec2.column_name;
    81             elsif cnt1<cnt then
    82                str:= str||rec2.column_name||',';
    83             end if;
    84             cnt1 := cnt1 + 1;
    85           end loop;
    86           close c1;
    87           str:=str||' from '||TAR_TAB||';'||
    88                ' r3 c3%rowtype; '||
    89                ' begin '||
    90                '   for r3 in c3 '||
    91                '   loop '||
    92                '     dbms_output.put_line(';
    93           cnt1:=1;
    94           open c1;
    95           loop
    96             fetch c1 into rec3;
    97             exit when c1%notfound;
    98             if cnt = cnt1 then
    99                str:= str||' r3.'||rec3.column_name;
    100             elsif cnt1<cnt then
    101                str:= str||' r3.'||rec3.column_name||
    102                     '||'',''||';
    103                cnt1 := cnt1 + 1;
    104             end if;
    105           end loop;
    106           close c1;
    107           str:=str||');'||
    108                ' end loop;'||
    109                ' exception '||
    110                '   when others then '||
    111                '     dbms_output.put_line(sqlerrm); '||
    112                ' end; ';
    113     end if;
    114     execute immediate(str);
    115     --dbms_output.put_line(str);
    116  exception
    117    when others then
    118      dbms_output.put_line(sqlerrm);
    119* END;
    120  /
    Procedure created.
    satyaki>
    satyaki>
    satyaki>
    satyaki>create table emp_t
      2     as
      3       select * from emp
      4       where rownum < 5;
    Table created.
    satyaki>
    satyaki>
    satyaki>desc emp;
    Name                                      Null?    Type
    EMPNO                                     NOT NULL NUMBER(4)
    ENAME                                              VARCHAR2(10)
    JOB                                                VARCHAR2(9)
    MGR                                                NUMBER(4)
    HIREDATE                                           DATE
    SAL                                                NUMBER(7,2)
    COMM                                               NUMBER(7,2)
    DEPTNO                                             NUMBER(2)
    satyaki>
    satyaki>
    satyaki>desc emp_t;
    Name                                      Null?    Type
    EMPNO                                              NUMBER(4)
    ENAME                                              VARCHAR2(10)
    JOB                                                VARCHAR2(9)
    MGR                                                NUMBER(4)
    HIREDATE                                           DATE
    SAL                                                NUMBER(7,2)
    COMM                                               NUMBER(7,2)
    DEPTNO                                             NUMBER(2)
    satyaki>set lin 1000
    satyaki>
    satyaki>select * from emp;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17-DEC-80        800                    20
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
          7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
          7566 JONES      MANAGER         7839 02-APR-81       2975                    20
          7654 MARTIN     SALESMAN        7698 28-SEP-81       1250       1400         30
          7698 BLAKE      MANAGER         7839 01-MAY-81       2850                    30
          7782 CLARK      MANAGER         7839 09-JUN-81       2450                    10
          7788 SCOTT      ANALYST         7566 19-APR-87       3000                    20
          7839 KING       PRESIDENT            17-NOV-81       5000                    10
          7844 TURNER     SALESMAN        7698 08-SEP-81       1500          0         30
          7876 ADAMS      CLERK           7788 23-MAY-87       1100                    20
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7900 JAMES      CLERK           7698 03-DEC-81        950                    30
          7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
          7934 MILLER     CLERK           7782 23-JAN-82       1300                    10
    14 rows selected.
    satyaki>
    satyaki>
    satyaki>select * from emp_t;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17-DEC-80        800                    20
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
          7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
          7566 JONES      MANAGER         7839 02-APR-81       2975                    20
    satyaki>
    satyaki>
    satyaki>set serveroutput on
    satyaki>
    satyaki>
    satyaki>begin
      2   compr_tab_dat('EMP_T','SCOTT','EMP','SCOTT');
      3  end;
      4  /
    No matched columns found....
    ORA-06535: statement string in EXECUTE IMMEDIATE is NULL or 0 length
    PL/SQL procedure successfully completed.
    satyaki>
    satyaki>
    satyaki>sho user;
    USER is "TRG2"
    satyaki>
    satyaki>
    satyaki>
    satyaki>
    satyaki>begin
      2       compr_tab_dat('EMP_T','TRG2','EMP','TRG2');
      3     end;
      4      /
      5  .
    satyaki>
    satyaki>ed
    Wrote file afiedt.buf
      1  begin
      2       compr_tab_dat('EMP_T','TRG2','EMP','TRG2');
      3* end;
    satyaki>/
    UnMatched Datas Are--
    7654,MARTIN,SALESMAN,7698,28-SEP-81,1250,1400,30
    7698,BLAKE,MANAGER,7839,01-MAY-81,2850,,30
    7782,CLARK,MANAGER,7839,09-JUN-81,2450,,10
    7788,SCOTT,ANALYST,7566,19-APR-87,3000,,20
    7839,KING,PRESIDENT,,17-NOV-81,5000,,10
    7844,TURNER,SALESMAN,7698,08-SEP-81,1500,0,30
    7876,ADAMS,CLERK,7788,23-MAY-87,1100,,20
    7900,JAMES,CLERK,7698,03-DEC-81,950,,30
    7902,FORD,ANALYST,7566,03-DEC-81,3000,,20
    7934,MILLER,CLERK,7782,23-JAN-82,1300,,10
    PL/SQL procedure successfully completed.N.B.: May be Any other member can come with much shorter or better technique than this one. But, according to your requirement - i'm posting it. Hope this will help you, or atleast give you some idea.
    Regards.
    Satyaki De.

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

  • Use of  ( * ) prefix before the table name

    Friends,
    Can anybody clear me the importance of prefixing the *(asterik) before the table name in the program.
    Eg. Tables: *mara,
                *cstk.
    Many Thanks,
    Albert.

    When you need two distinct work areas of the same database table in your program, you can use two tables declarations like
    Tables: mara, *mara.
    Typical use is on a screen, that has a table control. Here same table fields may appear on the main screen as well as in the table control. You use normal work area ( mara) to refer to main screen fields and the other work area ( *mara) for table control fields.

Maybe you are looking for

  • SQL Loader Multibyte character error

    Hello, Oracle Database 11g Release 11.2.0.2.0 - 64bit Production Database Characterset: WE8MSWIN1252 To load an utf8 File (UTF-8 Unicode text) i use option characterset UTF8 in controlfile. All went fine until in textfile the column is filled up with

  • HT1386 my phone will no longer turn all the way on or sinc... It just says activation required.

    My I phone will no longer turn on all the way or conect with my computer all the way to sinc.... keeps saying "activation required"? How do I activate?

  • TSQL Merge - Multiple statements after THEN

    I'm using a MERGE statement to merge two tables. When I have a match in keys, but the data is different I want to inactivate the old/existing record with an update statement where I fill the EndDate column with GetDate() and the Active active with fa

  • How do I get rid of this settings notification?

    After I updated to 7.0.3, I got a 1 notification on my Settings icon. I have been through every menu in settings, and I cannot find out what the notification is for. How do I get rid of it?

  • Creative zen not detected and freeze at creative l

    I got firmware problem and tried to reload firmware.when i was doing it, my zen vision got freeze at creative logo and now i can't excess anything. i can't see that recovery option,firmware update option, format option too...and my mp3 player is not