Querying MS-SQL Tabel in Java...

I am trying to display the contents of a table found in and MS-SQL server. I think my code works properly for connecting up with the server, however, when I try to display the field names in use in the table all I get is "null" for each entry in the array (String array for field names). Then Java bums out with "NullPointerException" error message.
Here is my code...
---===DatabaseObject.java===---
import java.sql.*;
import java.lang.*;
import java.util.*;
public class DatabaseObject
{//A class to simplifiy the use of database operations within Java where all database related
//are contained within one single object.
     private static Connection con = null;
     private static Statement stmt = null;
     private static ResultSet rs = null;
     private static ResultSetMetaData rsmd = null;
     private static Vector results = null;
     public DatabaseObject()
     public static void startConnection(String drvrName, String url, String loginID, String pwd)
     {// start SQL connection with server
          //Load the driver
          try
               Class.forName(drvrName);
               System.err.println(drvrName);
          catch(java.lang.ClassNotFoundException e)
               System.err.println("for:ClassNotFoundException:" + e.getMessage());
          //Make the connection
          try
               System.err.println(url);
               con = DriverManager.getConnection(url, loginID, pwd);
          catch(SQLException ex)
               System.err.println("con: SQLException: " + ex.getMessage());
     public static void queryTable(String tableName)
     {//Sends SQL SELECT command to database server and retrieves information as string array.
          //build up statement          
          String selectStatement = "SELECT *" + " FROM " + tableName;
          //send statement
          try
               stmt = con.createStatement();
               rs = stmt.executeQuery(selectStatement);
               rsmd = rs.getMetaData();
          catch(SQLException ex)
               System.err.println("query SQLException: " + ex.getMessage());
          //retrieve infromation
          int colNum = 0;
          String[] fieldName = null;
          try
               colNum = rsmd.getColumnCount();
               fieldName = new String[colNum - 1];
               for(int i=0; i < colNum; i++)
                    fieldName[i] = rsmd.getColumnName(i);
          catch(SQLException ex)
               System.err.println("info retrieval SQLException: " +ex.getMessage());
          /*Debug Section
          if (fieldName != null)
               for(int i = 0; i < colNum; i++)
                    System.out.println(fieldName);
          else
               System.out.println("No field names!");
          String record = "";
          results = new Vector();
          try
               while (rs.next())
                    record = "";
                    for(int i=0; i < colNum; i++)
                         record += rs.getString(fieldName[i]);
                    results.addElement(record);          
          catch(SQLException ex)
               System.err.println("record info SQLException: " + ex.getMessage());
     public static void Display()
          if (results != null)
               String s = "";
               for(int i=0; i < results.size(); i++)
                    s = (String) results.elementAt(i);
                    System.out.println(s);
          else
               System.out.println("No results to display.");
---===Main.java===---
public class Main
     public static void main(String[] args)
          DatabaseObject dbo = new DatabaseObject();
          String srvrName = ...;
          String loginID = ...;
          String pwd = ...;
          String url = "jdbc:odbc:" + srvrName;
          String drvrName = "sun.jdbc.odbc.JdbcOdbcDriver";
          dbo.startConnection(drvrName, url, loginID, pwd);
          dbo.queryTable(...);
          dbo.Display();

I changed:
fieldName<i> = rsmd.getColumnName(i);
to:
fieldName<i> = rsmd.getColumnName(i+1);
...and it worked!!
Thanks.

Similar Messages

  • Calling SQL Loader in Java

    I am writing a Java application running on SUN Solaris to perform data feed from a number of csv files to ORACLE. I am to use SQL Loader to perform the loading. What I need is to kick off the SQL Loader in my code. My question is how to kick off the SQL Loader in Java.
    One of option I am thinking is using RunTime.Exec(). Is the following code workable?
    runtime.exec( "sqlldr CONTROL=foo.ctl, LOG=bar.log, USERID=scott/tiger" );
    Althernatively should I write a Oracle store procedure to call the SQL Loader and Java call the store procedure?
    Any thoughts and directions are welcome!
    Regards,

    Hi,
    Can't you achieve the same thing using this
    Class.forName("Driver");
    Connection ocon=DriverManager.getConnection("url");
    Once you have ocon then you can execute any query.
    If this is not what you want,can you explain what SQLLoader means here?
    Regards
    Vicky

  • Is XML-SQL Utility for Java run on Client Side?

    A question about the XML-SQL Utility for Java
    When a client program connect to a Oracle database (the clinet program and Oracle DB is run on two different machine. Oracle 8i is used) and use the oracle.xml.sql.query.OracleXMLQuery Class (form the XSU) to generate XML by given a SQL query. I want to know the transforation process is execute in the Clinet side or the database?
    Is there any method that i can retrieve the XML directly from the database rather then doing the transformation form the Client side?

    Set JDK_HOME to the directory where you install your JDK (Java Development Kit).
    So instance, I've install JDK1.1.8 on my
    C drive so
    set JDK_HOME=c:\jdk1.1.8;c:\jdk1.1.8\bin

  • The troubles with creating SQL function in Java

    Hi!
    I use Oracle 10g and connect to it from Java application. I need in creating SQL functions from Java code.
    In Java I have:
    Statement stm = null; try{     stm = dbConnection.createStatement();     stm.executeUpdate( query ); }catch(SQLException ex){     throw ex; }finally{     try{ stm.close(); }catch(Exception ex){ stm.close(); } }
    And I'm passing the next SQL function:
    create or replace function get_me return number is
    result number;
    begin
    select 5 into result from dual;
    return result;
    end;
    This code is run successful, but I can't call this funtion, because it has status Invalid
    I'm looked the next error: PLS-00103: Encountered the symbol "" when expecting one of the following: . @ % ; is authid as cluster order using external character deterministic parallel_enable pipelined aggregate
    But I don't understand, What the matter? From Oracle Enterprise Manager I can create this function without problems. So, I wrote the wong Java code. Also, I can't find my error :(
    May be, do u have the some ideas?
    Thank you very much!

    Post the whole pl/sql code please.
    To run PL/SQL from within java you'll need callablestatement.
    [here |http://www.idevelopment.info/data/Programming/java/jdbc/PLSQL_and_JDBC/CallPLSQLFunc.java] an example : http://www.idevelopment.info/data/Programming/java/jdbc/PLSQL_and_JDBC/CallPLSQLFunc.java

  • Sql exception from java

    Hi,
    When running the below query from sqlyog it works OK but when running from java I got exception.
    What can cause this difference ?
    The query :
    create temporary table TempTable1 SELECT salaries.salary AS `salary`,salaries.emp_no AS `emp_no`,salaries.from_date AS `from_date`,MAX(salaries.salary) AS `func` FROM `salaries` WHERE salaries.to_date = '9999-01-01'
    The exception:
    com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Column 'salary' cannot be null
    Thanks

    Below is the code.
    When run from sqlyog is works OK.
    Thanks
    The code :
    package client;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    public class test {
         * @param args
         * @throws ClassNotFoundException
         * @throws IllegalAccessException
         * @throws InstantiationException
         * @throws SQLException
         public static void main(String[] args) throws InstantiationException,
                   IllegalAccessException, ClassNotFoundException, SQLException {
              String username = "root";
              String password = "";
              Class.forName("com.mysql.jdbc.Driver").newInstance();
              java.sql.Connection connection = DriverManager.getConnection(
                        "jdbc:mysql://localhost:3306/employees-thin", username,
                        password);
              Statement statement = connection.createStatement();
              statement
                        .execute("create temporary table TempTable1 SELECT salaries.salary AS `salary`,salaries.emp_no AS `emp_no`,salaries.from_date AS `from_date`,MAX(salaries.salary) AS `func` FROM `salaries` WHERE salaries.to_date = '9999-01-01'");
    Exception in thread "main" com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Column 'salary' cannot be null
         at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:931)

  • How to write exact query from sql to oracle?

    Hi all,
    hope doing well,
    sir i am using one query in sql that is
    declare @earlyleavers varchar(max), @earlyleavers1 int
    select @earlyleavers1 = DATEDIFF(Minute,'1900/01/01 10:00:00.000','1900/01/01 11:00:00.000')
    select @earlyleavers = CONVERT(char(8),DATEADD(n,@earlyleavers1,0),108)
    print @earlyleavers
    and i am getting the result like this
    01:00:00
    how to get the same result in oracle
    please help me.
    thanks in advance.

    952646 wrote:
    sir i need result in this format 01:00 not in 1 format.The name is Billy and not "sir". :-)
    Is "01:00" a string format or an elapsed time format?
    The number that the above code returns is decimal hours. So a number value of 1.5 means 1h30m or 1:30 or however you need to render that.
    And that is the question. Is this a rendering issue? Must the result be rendered in a specific format?
    If so, then this is not a SQL or PL/SQL issue. The server returning decimal hours is acceptable. The client (e.g. C#/Java code) needs to decide how to format and render this meaningful value. Keep in mind that if the sever code returns "1.30" or "1:30" for example, these are string/text data and pretty much meaningless. And it does not make sense for server code to return meaningless text strings to the client.
    If the client expects a duration and not a numeric data type, then the server code should return a value of the INTERVAL DAY TO SECOND data type.
    This data type specifically exists to contain duration values between to dates or times.
    In this case, the server code will expect the host (C#/Java) variable to be of data type INTERVAL DAY TO SECOND. The server code will look something as follows:
    SQL> declare
      2          earlyleavers    interval day to second;
      3  begin
      4          earlyleavers := NumToDSinterval(
      5                                  (to_date('1900/01/01 11:00:00','yyyy/mm/dd hh24:mi:ss') -
      6                                  to_date('1900/01/01 10:00:00','yyyy/mm/dd hh24:mi:ss') ) * 24,
      7                                  'hour'
      8                          );
      9 
    10          dbms_output.put_line( to_char(earlyleavers) );
    11  end;
    12  /
    +00 01:00:00.000000
    PL/SQL procedure successfully completed.
    SQL>An interval-to-string conversion function is used (with default formatting) to "print" the interval value via DBMS_OUTPUT. The default format includes days and a sign to indicate a positive or negative interval. Look at the SQL Reference manual for the format masks that can be used.
    The important thing is to treat data values correctly using the most appropriate type. And intervals should either be a decimal day/hour/minute numeric type, or an actual interval type.

  • PL/SQL Object Type - Java oracle.jbo.domain

    PL/SQL Object Type <-> Java oracle.jbo.domain
    can anybody help me, getting my domains to work?
    Following scenario:
    in pl/sql we have an object type called MULTI_LANGUAGE. This type is used for storing multilingual texts as nested table in one(!) column.
    So the object MULTI_LANGUAGE contains a member variable LANGUAGE_COLLECTION of type LANGUAGE_TABLE, which itself is a nested table of objects
    of the type LANGUAGE_FIELD (this again is only a language id and the corresponding content)
    Also the methods setContent(langID, langContent) and getContent(langId) are defined on Object MULTI_LANGUAGE.
    For example: Table having primary key, 2 other columns and one column of object type MULTI_LANGAGE (=nested table of objects)
    |ID|Column1|Column2|  multilingual Column  |
    |--|---------------------------------------|
    |  |       |       |  -------------------  |
    |  |       |       | | 1 | hello         | |
    |  |       |       |  -------------------  |
    |1 | foo   | bar   | | 2 | hallo         | |   <- Row Nr 1
    |  |       |       |  -------------------  |
    |  |       |       | | 3 | ola           | |
    |  |       |       |  -------------------  |
    |--|-------|-------|-----------------------|
    |  |       |       |  -------------------  |
    |  |       |       | | 1 | world         | |
    |  |       |       |  -------------------  |
    |2 | abc   | def   | | 2 | welt          | |   <- Row Nr 2
    |  |       |       |  -------------------  |
    |  |       |       | | 3 | ???  ;-)      | |
    |  |       |       |  -------------------  |
    |--|-------|-------|-----------------------|Now i've tried to modell this structure as an oracle.jbo.domain.
    class MultiLanguage extends Struct having this StructureDef:
    attrs[(0)] = new DomainAttributeDef("LanguageColl", "LANGUAGE_COLL", 0, oracle.jbo.domain.Array.class, 2003, "ARRAY", -127, 0, false, "campusonlinepkg.common.LanguageField");
    and
    class LanguageField extends Struct having this StructureDef:
    attrs[(0)] = new DomainAttributeDef("Id", "ID", 0, oracle.jbo.domain.Number.class, 2, "NUMERIC", -127, 0, false);
    attrs[(1)] = new DomainAttributeDef("Content", "CONTENT", 1, java.lang.String.class, 12, "VARCHAR", -127, 4000, false);
    Is there anything wrong with this StructureDef?
    When running the BC-Browser with -Djbo.debugoutput=console -Djbo.jdbc.driver.verbose=true parameters I get suspect warnings when browsing the records
    [196] Executing FAULT-IN...SELECT NR, NAME FROM B_THESAURI BThesauri WHERE NR=:1
    [197] SQLException: SQLState(null) vendor code(17074)
    [198] java.sql.SQLException: Ungültiges Namensmuster: XMLTEST.null
    ...snip: detail of stack...
    [240] SQLException: SQLState(null) vendor code(17060)
    [241] java.sql.SQLException: Deskriptor konnte nicht erstellt werden: Unable to resolve type "null"
    ...snip: detail of stack...
    [280] Warning:No element type set on this array. Assuming java.lang.Object.
    (XMLTEST is the name of the schema)
    Seems as if the framework can't read the TypeDescriptor or does not know which descriptor to read (XMLTEST.null??)
    Do I have to implement my own JboTypeMap?
    Please help, I'm stuck.
    Thanks in advance, Christian

    Thanks for your suggestion, but it seems to me as if there is one level missing.
    in pl/sql I have following structure:
    Struct MULTI_LANGUAGE (Object type) - outermost
      Array LANGUAGE_TABLE (nested table type)
        Struct LANGUAGE_FIELD (Object type simple) - innermostthe reason why i had to wrap another struct around the array was because it is not possible to define methods on a nested table. this is only possible on objects.
    on the outermost object type (which holds the array of language fields) I needed to define following 2 methods for direct access:
    getContent (langId in number) returns varchar2
    setContent (langId in number, langContent in varchar2)
    I would like to rebuild the same structure in java, because newly written java code should live in perfect harmony with legacy pl/sql code ;-)
    Both applications (Java and pl/sql) have to access the same data as long as migration to java goes on.
    Is this nested structure too much for a Domain?
    Any other suggestions?
    Thanks again, Christian

  • How i connect to SQL server using java?

    hi every body
    i need to connect to a sql server database using java
    i do not know sql driver in java
    plz help me
    thanks

    This is certainly the wrong forum for that question. Search in the JDBC forum. This has been asked and answered many times.

  • How do i connect to sql server using java?

    hi ever body
    i need to connect to sql server using java
    what is the driver i will use?
    thanks

    Microsoft make a jdbc driver and it is readily available through MSDN. Here is a link http://msdn2.microsoft.com/en-us/data/aa937724.aspx. Whatever jdbc driver you are looking for, Google it, and if it exists you'll find it in 10 seconds.

  • Accessing MS Sql Server with Java classes - problem connecting to socket

    I found an example at this location which uses java classes to connected to MS Sql Server.
    http://search400.techtarget.com/tip/1,289483,sid3_gci1065992,00.html
    --bummer - it is a login location - so I will include the article
    Anyway, the example is using Websphere, but I am still on Jbuilder (will get wsad soon). So I planted the classes from the example in
    C:\Borland\JBuilder\jkd1.4\jre\lib\ext\...the classes
    Then I copied the code from the example to my jpx project and got an error that it could not connect to the socket. The only thing I changed in the code was the connection string:
    --original string from example:
    Connection connection = DriverManager.getConnection("jdbc:microsoft:sqlserver://1433", "");
    I was getting an error with the 2 argument version of DriverManager - and the second argument here was empty (properties argument). Here was my connection string:
    Connection connection = DriverManager.getConnection("jdbc:microsoft:sqlserver://Myserver:1433;User=sa;Password=");
    I am only using the 1 argument version of DriverManager. Note that the password=" is blank because my RnD workstation is standalone - no one accesses the sql server except me - so no password. I also left out the last semicolon I noticed. Any suggestions appreciated how I could fix this.
    Thanks
    source of article:
    http://search400.techtarget.com/tip/1,289483,sid3_gci1065992,00.html
    iSeries 400 Tips:
    TIPS & NEWSLETTERS TOPICS SUBMIT A TIP HALL OF FAME
    Search for: in All Tips All search400 Full TargetSearch with Google
    PROGRAMMER
    Sample code: Accessing MS SQL Server database from the iSeries
    Eitan Rosenberg
    09 Mar 2005
    Rating: --- (out of 5)
    Nowadays with the help of Java the iSeries can be integrated with other databases quite easy. This tip shows you how. The code included here uses the free Microsoft driver that can be downloaded from here. (SQL Server 2000 Driver for JDBC Service Pack 3)
    If your SQL server does not include the Northwind Sample Database you can find it here.
    http://www.microsoft.com/downloads/details.aspx?familyid=07287b11-0502-461a-b138-2aa54bfdc03a&displaylang=en
    The download contains the following files:
    msbase.jar
    mssqlserver.jar
    msutil.jar
    Those files needs to be copied to the iSeries directories (/home/r_eitan/ExternalJARs).
    Here's the directory structure (on the iSeries) for this sample:
    /home/r_eitan/ExternalJARs - Microsoft files (msbase.jar,mssqlserver.jar,msutil.jar)
    /home/r_eitan/JdbcTest02 - My code (Main.java,Main.class)
    The Java code
    import java.sql.*;
    import java.io.*;
    class Main {
    * Connect to Microsoft SQL server and download file northWind.products as tab
    * seperated file. (products.txt)
    public static void main(String args[]) {
    try {
    PrintStream outPut = new PrintStream(new BufferedOutputStream(new FileOutputStream("products.txt")));
    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
    //Connection connection = DriverManager.getConnection("jdbc:microsoft:sqlserver://1433", "");
    Connection connection = DriverManager.getConnection("jdbc:microsoft:sqlserver://Myserver:1433;User=sa;Password=");
    System.out.println("Connection Done");
    connection.setCatalog("northWind");
    String sqlCmdString = "select * from products";
    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery(sqlCmdString);
    ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
    int columnCount = resultSetMetaData.getColumnCount();
    // Iterate throught the rows in resultSet and
    // output the columns for each row.
    while (resultSet.next()) {
    for (int index = 1; index <=columnCount; ++index)
    String value;
    switch(resultSetMetaData.getColumnType(index))
    case 2 :
    case 3 :
    value = resultSet.getString(index);
    break;
    default :
    value = """ + resultSet.getString(index) + """;
    break;
    outPut.print(value + (index < columnCount ? "t" : ""));
    outPut.println();
    outPut.close();
    resultSet.close();
    connection.close();
    System.out.println("Done");
    catch (SQLException exception)
    exception.printStackTrace();
    catch (Exception exception)
    exception.printStackTrace();
    --------------------------------------------------------------------------------------------------

    My guess is that the server's host name isn't right. It necessarily (or even usually) the "windows name" of the computer. Try with the numeric IP address instead (type "ipconfig" to see it).
    First aid check list for "connection refused":
    - Check host name in connect string.
    - Check port number in connect string.
    - Try numeric IP address of server host in connect string, in case name server is hosed.
    - Are there any firewalls between client and server blocking the port.
    - Check that the db server is running.
    - Check that the db server is listening to the port. On the server, try: "telnet localhost the-port-number". Or "netstat -an", there should be a listening entry for the port.
    - Try "telnet serverhost the-port-number" from the client, to see if firewalls are blocking it.
    - If "telnet" fails: try it with the numeric ip address.
    - If "telnet" fails: does it fail immediately or after an obvious timeout? How long is the timeout?
    - Does the server respond to "ping serverhost" or "telnet serverhost" or "ssh serverhost"?

  • SQL query (pl/sql function body returning query) performance issue

    I create my report in building my sql instruction with ( SQL Query pl/sql function body returning sql query );
    My report take more than 20 seconds however if i did a cut and paste with the sql code in TOAD the same sql take 1 second.
    To try to discover the source of the problem; i take the sql generated by the function and i create another report ( sql query ) this new report take 2 seconds.
    My query is very big 25,000 characters with database link.
    What is the difference between SQL-quey and sql-query(pl/sql function body returning sql query)
    Thanks
    Marc

    Marc,
    Firstly...don't compare the timings from Toad, since often Toad only fetches the first few records for you (i.e. it pages them).
    Secondly....the database link could be a factor here, but without seeing your query it's too hard to say.
    Can you post the query somewhere (on a webserver say)?

  • Connect to MS Sql Server from Java Source

    Hi,
    Is there any way I could connect to ms sql server from Java source? I know I can call java source from function thats easy but what I really want is capability to connect to non-oracle(MS SQL server) from my java source and then call it from function.
    I don't know if JDBC driver for SQL server is even installed/available. Is there a way I could find it out form my IDE? I know sqlJ does compile but I have never used sqlj. help!!!
    Sinha

    You'll probably have better luck in a Java forum or a Microsoft forum.

  • Different output of same query in SQL Server and Oracle

    I have two tables table1 and table2
    --table1 has two columns c1 int and c2 varchar. there are not constraints added in it. it has data as given below
    c1     c2
    6     d
    5     j
    102     g
    4     g
    103     f
    3     h
    501     j
    1     g
    601     n
    2     m
    --table2 has only one column c1 int. there are not constraints added in it. it has data as given below
    c1
    6
    1
    4
    3
    2
    now when i run below given query in sql server and oracle it gives me different result
    select *
    from table1
         inner join (SELECT ROW_NUMBER() OVER (order by c1 ASC) AS c1 from table2) table2 on table2.c1=table1.c1
    sql server output
    c1     c2     c1
    1     g     1
    2     m     2
    3     h     3
    4     g     4
    5     j     5
    oracle output
    C1 C2 C1
    5 j 5
    4 g 4
    3 h 3
    1 g 1
    2 m 2
    If you notice the first column in both output. It is sorted in sql server and not in oracle.
    Why it is behaving differently in oracle? Is there any way I can solve this in oracle?
    Thanks,
    Jigs

    It is NOT behaving "differently" in Oracle; you just haven't specified an order that you expect your results to be in, so you're going to get output in whatever order the database fancies displaying it (ie. no guarenteed order). This is an artifact of how the database chooses to put together the data, and different databases (or even datasets within the same database) can and most likely will behave differently.
    Even SQL Server won't guarentee to always get your data in an ordered fashion if you exclude the order by clause, even if you think it has always output the data in an ordered fashion.
    Your solution is to add an order by clause, in BOTH databases, to force the order of the output data.

  • SQL Query (pl/sql function body returning Sql query)

    Hi All,
    I have created a region of "SQL Query (pl/sql function body returning Sql query)" type and it is working fine , but when I am migrating(export /import) this application from development to systest environment ,
    It gives error for this region :
    Error ERR-1101 Unable to process function body returning query.
    OK
    ORA-06550: line 1, column 52: PLS-00306: wrong number or types of arguments in call to 'FU_TRADE_REPORT_QUERY' ORA-06550: line 1, column 45: PL/SQL: Statement ignored
    Any pointer ...why this is happening.
    Thanks
    Dikshit

    If your function is a stored function that is called from within APEX (function body not coded into the app itself), have you made sure that the function has been created and compiles ok prior to installing your apex app.
    If there are some dependency issues between other PL/SQL units or database objects that are causing your function not to be compiled, you apex install will fail as you are trying to reference an uncompelled bit of pl/sql.
    Let me know how you get on
    Regards
    Duncan

  • SQL Query(PL/SQL Function Returning SQL Query)

    I am trying to write a dynamic report using SQL Query(PL/SQL Function Returning SQL Query).
    I can get the report to run but I need to concatinate some columns into one, seperated by a comma or a dash.
    I have tried select *****||','||***** alias
    also select *****||'-'||***** alias
    but I always get an error.
    Is there a way of doing this please
    Gus

    This is my full query
    declare
    v_query varchar2(4000);
    begin
    if :P63_TRAN_INFO = 2 THEN
    v_query := 'select
         A.FILENR,
         A.EXERCISENAME,
    A.STARTDATE,
    A.ENDDATE,
         A.UNIT,
    A.ACCADDRESSES, B.ADDRESS, B.ADDRESS_1, B.POST_CODE, B.TOWN,
         A.EXERCISEAREAS,
         A.TOTALVEHICLES,
    A.TOTALTROOPS+A.RNTOTALTROOPS+A.RAFTOTALTROOPS TOTALTROOPS,
    A.CAR, A.MINIBUS, A.HGV,
    A.NAMERANK, A.ADDRESS, A.ADDRESSI, A.ADDRESSII, A.POSTCODE,
    A.TRANSIT,
    A.INFOONLY
    from     BFLOG_AT A, BFLOG_ACCADDRESS B
    WHERE A.ACCADDRESSES = B.NAME
    AND A.STARTDATE >= :P63_START_DATE
    AND A.ENDDATE <= :P63_END_DATE
    AND A.AUTHORISED = 1
    AND A.INFOONLY = 1' ;
    END IF;
    RETURN v_query;
    END;
    This query runs ok, but if I try changing it to the code below with fields concatinated, then it fails
    declare
    v_query varchar2(4000);
    begin
    if :P63_TRAN_INFO = 2 THEN
    v_query := 'select
         A.FILENR,
         A.EXERCISENAME,
    A.STARTDATE,
    A.ENDDATE,
         A.UNIT,
    A.ACCADDRESSES||','||B.ADDRESS||','||B.ADDRESS_1||','||B.POST_CODE||','||B.TOWN ADDRESS,
         A.EXERCISEAREAS,
         A.TOTALVEHICLES,
    A.TOTALTROOPS+A.RNTOTALTROOPS+A.RAFTOTALTROOPS TOTALTROOPS,
    A.CAR, A.MINIBUS, A.HGV,
    A.NAMERANK, A.ADDRESS, A.ADDRESSI, A.ADDRESSII, A.POSTCODE,
    A.TRANSIT,
    A.INFOONLY
    from     BFLOG_AT A, BFLOG_ACCADDRESS B
    WHERE A.ACCADDRESSES = B.NAME
    AND A.STARTDATE >= :P63_START_DATE
    AND A.ENDDATE <= :P63_END_DATE
    --AND (A.EXERCISEAREAS LIKE "GAP, OA, OAL")
    --OR (A.EXERCISEAREAS LIKE "Harz")
    AND A.AUTHORISED = 1
    AND A.INFOONLY = 1' ;
    END IF;
    RETURN v_query;
    END;
    Cheers
    Gus

Maybe you are looking for