Hibernate Query vs PreparedStatement for SQL

Hi,
I am using Hibernate for DAO classes, which i am using for the basic CRUD operations. But for complex queries with complex joins i am writing the SQL.
In such case whether it is better to use the Query.createSQLQuery(String sql) to invoke the SQL or better to use the PreparedStatement since i am invoking only the SQL as supposed to HQL by getting the connection from the Hibernate Session. Since the PreparedStatement is precompiled it may be faster than invoking the SQL through the Query.createSQLQuery(String sql)? or using the Session.getNamedQuery(QUERY_NAME)? Please let me know your opinion on this.
Thanks

Whether you use Hibernate, ODBC, BDE, or Funky Foo's SQL client library, Oracle does not give a damn.
It receives a statement from the client. This can either be SQL or an anonymous PL/SQL block. It parses it as a cursor. It then provides the client with a cursor handle to reference the cursor.
The cursor is essentially a program. If it has bind variables, it is a program that accepts parameter input. This allows the very same program to be executed multiple times with different input parameters. For example, executing the same INSERT SQL cursor for different values and inserting multiple rows using the very same cursor.
A cursor can also (like a program), produce output. An example is a SELECT cursor - where the fetch interface of the cursor enables the caller to consume the output of the cursor.
So what is optimal in this respect? First and foremost cursors that are created using and used with bind variables. Secondly, re-using the very same client cursor handle (and not just the same server side SQL cursor) where possible (e.g. like repeating the same SQL INSERT statement with different values).
The question to asked is whether the method you select to use on the client side - be that Hibernate or Funky Foo SQL, support this?
The consideration to make is the following. Why code SQL in the client side? SQL is executed on the server-side - refers to server side data structures and needs to be tuned on the server. Put that code in a client and it significantly increases the complexity and decrease the flexibility of SQL.
The alternative (and recommended approach) is to use PL/SQL to encapsulate all SQL. Instead of the client (and client programmer) needing to know SQL, a PL/SQL call interface is provided with calls like GetInvoice() to return a single specific invoice, or GetInvoiceByDate() that returns selected invoices for a date range. The PL/SQL code creates the SQL cursor and returns the client cursor handle as a reference cursor to the caller.
This also allows business and validation logic to be implemented in the PL/SQL call interface to protect data integrity and business transaction sanity. A database structure change requires the SQL inside a PL/SQL procedure to be changed - without having to touch the client code. Likewise, SQL can be tuned and improved without having recompile a single byte of client code. And the same PL/SQL call interface services all clients - unlike multiple Java clients duplicating the same SQL (and not always correctly) to do the same thing, or having to duplicate and repeat the same data validation and business rule logic.

Similar Messages

  • PreparedStatement for SQL using IN (SQL Server 2000)

    Hi, guys
    How can I create a preparedStatement for a query using IN operator, which allow me to insert any number of parameters?
    eg: SELECT * FROM Students WHERE lastname IN (?, ?, ?, ....)
    Thanks
    jacklty

    Hi, I have found a simpler way of doing this.
    private static final String QUERYSTRING = "SELECT * from junk_table "+
                                            " WHERE status in (:x) " ;
    <..somewhere later in the code...>
    StringBuffer tempBuffer=new StringBuffer(QUERYSTRING);
    //Find :1 and replace with a comma separeted list of stauts
    tempBuffer.replace(tempBuffer.indexOf(":x"),tempBuffer.indexOf(":x") + ":x".length(),
    new String(System.getProperty("status")));
    In short, here I am creating my own bind parameters named as :x,:y (lack of imagination on my part...) and then replacing the values of those values with the comma-separated value before actually creating the PreparedStatement.
    Hope this works
    --Ved                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Why can't i use "INNER JOIN" in a query for SQL Server with JDBC??????

    Hi,
    I'm trying to execute some SQL queries and I just don't understand what's wrong.
    I�m using Tomcat and SQL Server in order to do this, but when I�m try to execute a query with a INNER JOIN statements Tomcat raise a SQL exception... at the very first time I thought there was a problem with database connection but I realize that a simple query to a table works pretty well. then I found out some problems with JDBC:ODBC.... so I install JDBC for SQL Server 2000 and test with the same simple query and works..... so, I come to a conclusion.... INNER JOIN or JOIN statements can't be used in JDBC..... please... somebody tell I�m wrong and give me a hand...
    I'm using TOMCAT 4 and JDK 1.4 SQL Server 2000
    Error occurs when executeQuery() is called.... not prepareStatement().... ??????
    Driver DriverRecResult = (Driver)Class.forName(driver).newInstance();
    Connection ConnRecResult = DriverManager.getConnection(DSN,user,password);
    PreparedStatement StatementRecResult = ConnRecResult.prepareStatement(query);
    ResultSet RecResult = StatementRecResult.executeQuery(); <---- Exception raise here
    So much tahnks in advance,

    That's exactly what I think, driver it's raising the exception, but I don't know why.... i test the same query with INNER JOIN directly from SQL Query Analyser and it's works perfectly, my problem ain't SQL, but JSP and JDBC 'cause i'm a newbie about these issues.
    Common sense tell me possible problems lie in SQLServer drivers 'cause i run the same pages on JRUN through jdbc:odbc and do works well, but by now i just depend on Tomcat.....
    I've installed SQL Server drivers for JDBC but i just find it doesn't work fully... could be the version of JDK i've installed? what version do i need?
    ( I'm running Tomcat 4 with JDK 1.4 & SQL Server 2000 W2K )
    thanks for reply.

  • Can we implement the custom sql query in CR for joining the two tables

    Hi All,
    Is there anyway to implement the custom sql query in CR for joining the two tables?
    My requirement here is I need to write sql logics for joining the two tables...
    Thanks,
    Gana

    In the Database Expert, expand the Create New Connection folder and browse the subfolders to locate your data source.
    Log on to your data source if necessary.
    Under your data source, double-click the Add Command node.
    In the Add Command to Report dialog box, enter an appropriate query/command for the data source you have opened.
    For example:
    SELECT
        Customer.`Customer ID`,
        Customer.`Customer Name`,
        Customer.`Last Year's Sales`,
        Customer.`Region`,
        Customer.`Country`,
        Orders.`Order Amount`,
        Orders.`Customer ID`,
        Orders.`Order Date`
    FROM
        Customer Customer INNER JOIN Orders Orders ON
            Customer.`Customer ID` = Orders.`Customer ID`
    WHERE
        (Customer.`Country` = 'USA' OR
        Customer.`Country` = 'Canada') AND
        Customer.`Last Year's Sales` < 10000.
    ORDER BY
        Customer.`Country` ASC,
        Customer.`Region` ASC
    Note: The use of double or single quotes (and other SQL syntax) is determined by the database driver used by your report. You must, however, manually add the quotes and other elements of the syntax as you create the command.
    Optionally, you can create a parameter for your command by clicking Create and entering information in the Command Parameter dialog box.
    For more information about creating parameters, see To create a parameter for a command object.
    Click OK.
    You are returned to the Report Designer. In the Field Explorer, under Database Fields, a Command table appears listing the database fields you specified.
    Note:
    To construct the virtual table from your Command, the command must be executed once. If the command has parameters, you will be prompted to enter values for each one.
    By default, your command is called Command. You can change its alias by selecting it and pressing F2.

  • Outer join query for SQL server from Oracle

    Hi All,
    My question is regarding making queries from Oracle to SQL Server database thorugh DBLink.
    In my oracle database I have a DBLink emp.world for SQL Server database.
    I need to query SQL Server data from oracle (so that this query can be combined with other oracle tables).
    Query is given below:
    SELECT
            a."EmpID" as "Employee ID",
            a."EmpStatus" "Employee Status"
            b."EmpSub" as "Employee Subjects"
    FROM
            [email protected] a
            left outer join [email protected] b on a."EmpID" = b."suEmpID"
    ORDER BY  a."EmpID";My problem is when I run the same query from oracle, it does not show the EmpID that does not exist in Subjects table, but when run from actual SQL Server database, it shows all the records.
    Samples are given below:
    Run from Oracle
    Employee ID      Employee Status     Employee Subjects
    101                     Active                     Maths
    102                     Active                     Maths
    102                     Active                     Physics
    104                   Inactive                  Chemistry
    Run form SQL Server
    Employee ID      Employee Status     Employee Subjects
    101                     Active                     Maths
    102                     Active                     Maths
    102                     Active                     Physics
    103                 Active                       NULL
    104             Inactive            ChemistryI am not sure why in oracle outer join for SQL server tables is not working. What is the right way for outer join in this case.
    I am using oracle database 10gR2 and SQL Server 2005.
    Please Help.
    Thanks.

    SELECT
    a."EmpID" as "Employee ID",
    a."EmpStatus" "Employee Status"
    b."EmpSub" as "Employee Subjects"
    FROM
    [email protected] a
    left outer join [email protected] b on a."EmpID" = b."suEmpID"
    ORDER BY a."EmpID";
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/queries006.htm#sthref3175
    From your description, it appears you may need a right outer join. You want to get back all the rows from 'B', not from 'A'. Try a right join and let us know.

  • Hibernate mapping XML files for the two SQL Server tables below.

    Hello all..,
    Question 1:
    I am working on a project that needs to support a database with an inherited legacy schema that you cannot change. The schema is provided below.Hibernate mapping XML files for the two SQL Server tables below. Please provide those two XML files. Assume some hypothetical package and class names. Assume that no "fancy" stuff such as lazy initialization, optimistic locking etc is needed at this time.
    CREATE TABLE [SURVEY_ANSWERS] (
    [ANSWER_ID] [int] IDENTITY (1,1) NOT NULL,
    [QUESTION_ID] [int] NOT NULL,
    [POSITION] [int] NULL,
    [TEXT] [varchar](350) NULL
    CREATE TABLE [dbo].[SURVEY_QUESTIONS] (
          [QUESTION_ID] [int] IDENTITY (1, 1) NOT NULL ,
          [TEXT] [varchar] (350) NULL
    GO
    ALTER TABLE SURVEY_ANSWERS
    ADD CONSTRAINT pk_SURVEY_ANSWERS PRIMARY KEY(ANSWER_ID,QUESTION_ID);
    ALTER TABLE [dbo].[SURVEY_QUESTIONS] ADD
           PRIMARY KEY  CLUSTERED
                [QUESTION_ID]
    GO
    ALTER TABLE [dbo].[SURVEY_ANSWERS] ADD
           FOREIGN KEY
                [QUESTION_ID]
          ) REFERENCES [dbo].[SURVEY_QUESTIONS] (
                [QUESTION_ID]
          )Question 2:
    Assume that you are working on a project developing, say, a banking application. You are the Architect and thinking that Hibernate ORM should be used for the entire access to the relational database. As usual, you have created (or auto-generated) a set of HBM XML files as well as POJOs for which you define the mappings. Assume now that a new requirement has just popped up. The system needs to be able to import new bank accounts and user information in bulk from a very large XML file at once and store it in the database. Assume the XML file contains all necessary information to populate fields in database tables. As performance is very important for this operation. Given this description, how would you approach the problem?
    Please describe briefly.
    -Thanks and regards
    Praveen Soni

    You're not fooling anyone Dennis_Mox. But nice try.Jeez, man. Mail me at denismox[at]yandex.ru, I will show you that exact test, dammit.

  • How to access the datasource window in SSRS for sql server 2008 R2 for writing my query without having to go through the wizard?

    I have used SSRS a lot years ago with Sql Server 2000 and Sql Server 2005. I have written external assemblies, ... But now I have to do this with Sql Server 2008 (R2 -- which I realize I am way behind the times already but ...)  in sql server 2000 and
    2005 there was a tab for datasource to the left of the tab for design which was to the left of the preview tab. How do I get to the datasource window in sql server 2008 (r2) ?
    I see that datasource explorer.  But where can I get to the datasource window to edit my queries and so forth for sql server 2008 (R2)?
    Thanks
    Rich P

    I think I found the answer to my question --- just right-click on the the Data Sources or Datasets for editing connections and dataset queries.  I'm guessing it gets even fancier with Sql Svr 2012 - 2014.    Man, that's the one thing
    about coding platforms -- you let it go for a few years and come back, and everything has changed (well, a lot of things).  Now I need to figure out how to add an external assembly to SSRS 2008 (R2).
    Rich P

  • Queries with date functions using PreparedStatement for multiple DB

    I am developing application that uses DB independant queries. I am using preparedstatement to process the queries. I need to use date functions for query selection criteria.
    for eg.
    selecting the list of employees who had joined in the last 15 days
    selecting list of employees who had joined between two dates etc.
    where Date Joined field is a Timestamp value. To extract date no DB specific function can be used.
    If I use setMonth, setYear etc.. to set params in the pstmt the query becomes complex in the above case. Can any one throw some light on how to do the above in preparedstatement or any other better alternative.
    Tx a lot

    Hi,
    I did not mean that way. I presume that there is a timestamp value (may be a date too) column in the table. Then based upon your requirement (say before 15 days) pass the value as date (or time stamp) in the query as a parameter.
    String qry = "select * from myTable where join_date <= ?";
    stmt.setDate(1,myDate); // this is where you will have to manipulate the value to suit your DB timestamp or date value; you will have compatibility issues with util.Date and sql.Date so use Calendar class to satisfy.Feel free to mail me if you need further clarifications to [email protected]
    Cheers,
    Sekar

  • Method for SQL statement

    I have repeated resultset object execute statements and would like to put them in a method if possible.
    The repeated part is:
    Resultset rs = statement.executeQuery("select max(id) from TableMain");
    rs.next();
    Here is an example of what I am doing now:
    Statement statement = connection.createStatement();
    if((a == 0) && (b > 0))
        Resultset rs = statement.executeQuery("select max(id) from TableMain");
        rs.next();
        a = rs.getInt(1);
        //my insert sql is here to insert into another table the value of the max id....
    else if((c > 0) && (d == 0))
        Resultset rs = statement.executeQuery("select max(id) from TableMain");
        rs.next();
        c = rs.getInt(1);
       //my insert sql is here to insert into another table the value of the max id....
    else if((f == 0) && (g > 0))
        Resultset rs = statement.executeQuery("select max(id) from TableMain");
        rs.next();
        f = rs.getInt(1);
       ///my insert sql is here to insert into another table the value of the max id....
    }I need help on my attempt below because I am not sure how to do it:
    public ResultSet getMaxId()
             Resultset rs = statement.executeQuery("select max(id) from TableMain");
             rs.next();
             return rs;
    }Call it like this:
    else if((f == 0) && (g > 0))
        getMaxId();
        f = rs.getInt(1);
       ///my insert sql is here to insert into another table the value of the max id....

    I don't see how it's repeated; all of those are mutually exclusive blocks, only one of them will run. The only thing you seem to be doing different is assigning the max id value to different variables.
    Statement statement = connection.createStatement();
        Resultset rs = statement.executeQuery("select max(id) from TableMain");
        int tempValue = 0;
        if ( rs.next() )
            tempValue = rs.getInt(1);
    if((a == 0) && (b > 0))
        a = tempValue;
    else if((c > 0) && (d == 0))
        c = tempValue;
    else if((f == 0) && (g > 0))
        f = tempValue;
       ///my insert sql is here to insert into another table the value of the max id....----------------------------------------------------------------
    People on the forum help others voluntarily, it's not their job.
    Help them help you.
    Learn how to ask questions first: http://faq.javaranch.com/java/HowToAskQuestionsOnJavaRanch
    (Yes I know it's on JavaRanch but I think it applies everywhere)
    EDIT: I don't know if you're doing it already but you should also use try-catch blocks and also, make sure you close your ResultSet, Statement and Connection in a finally block.
    And where you have parameters for the query, use PreparedStatement instead of building the query yourself.
    Edited by: nogoodatcoding on Oct 12, 2007 7:43 AM

  • Use evdre to query data from a SQL View

    Hi all
    I believe that it is possible to use evdre to query data from a SQL View. If this is possible then how does one go about setting it up in the evdre options (assuming that the view has already been created)?
    Regards,
    Byron

    Byron,  perhaps this is no longer supported, it might be worth opening up a case at service.sap.com on this.  However, I did find the following on Page 11 of the "Usages and Considerations of EVDRE" pdf file.  This doc is imbedded in the helpfile for BPC 7 SP5 (which was released in August of 2009, well after note 1315011 was last updated.
    It looks like you are limited to one custom view per application, since you have to name the view in a parameter at the APPLICATION level.  Go into BPC Administration, login to the application related to the custom view, choose "Set Application Parameters" and enter the name of the view to the Application Parameter called "EVDRE_QUERYVIEWNAME"  If it is not listed, go ahead and create it at the bottom of the Application parameter screen.
    Also:  I interpreted the following info from Page 10 of the same doc:
    In your EVDRE, set the following options:
    QueryEngine: MANUAL
    QueryType:  enter either NEXJ  OR TUPLE  see below:
    NEXJ  - Use two-dimensional queries using the nonemptycrossjoin function
    TUPLE  - Use two-dimensional queries using tuples"
    And I'm assuming you'd enter a Y for the following two parameters:
    QueryViewName
    "..to enforce the query engine to use a used-defined SQL view of the fact tables, when trying to read the values using SQL queries. This option is typically used in conjunction with the SQLOnly option (see below). "
    Option SQLOnly
    "..to enforce the query engine to only execute SQL queries, when reading data. This can be achieved using this option."

  • PL/SQL function body returning SQL query - ORA-06502: PL/SQL: numeric or value error

    I'm attempting to dynamically generate a rather large SQL query via the "PL/SQL function body returning SQL query" report region option.  The SQL query generated will possibly be over 32K.  When I execute my page, I sometimes receive the "ORA-06502: PL/SQL: numeric or value error" which points to a larger than 32K query that was generated.  I've seen other posts in the forum related to this dynamic SQL size limitation issue, but they are older (pre-2010) and point to the 32K limit of the DNS (EXECUTE IMMEDIATE) and DBMS_SQL.  I found this post (dynamic sql enhancements in 11g) which discusses 11g no longer having the 32K size limitation for generating dynamic SQL.  Our environment is on 11gR2 and using ApEx 4.2.1.  I do not know which dynamic SQL method -- DNS or DBMS_SQL -- ApEx 4.2.1 is using.  Can someone clarify for me which dynamic SQL method ApEx uses to implement the "PL/SQL function body returning SQL query" option?
    As a test, I created a page on apex.oracle.com with a report region with the following source:
    declare
      l_stub varchar2(25) := 'select * from sys.dual ';
      l_sql  clob := l_stub || 'union all ';
      br     number(3) := 33;
    begin
      while length ( l_sql ) < 34000 loop
        l_sql := l_sql || l_stub || 'union all ';
      end loop;
      l_sql := l_sql || l_stub;
      for i in 1 .. ceil ( length ( l_sql ) / br ) loop
        dbms_output.put_line ( dbms_lob.substr ( l_sql, br, ( ( i - 1 ) * br ) + 1 ) );
      end loop;
      return l_sql;
    end;
    The dbms_output section is there to be able to run this code in SQL*Plus and confirm the size of the SQL is indeed larger than 32K.  When running this in SQL*Plus, the procedure is successful and produces a proper SQL statement which can be executed.  When I put this into the report region on apex.oracle.com, I get the ORA-06502 error.
    I can certainly implement a work-around for my issue by creating a 'Before Header' process on the page which populates an ApEx collection with the data I am returning and then the report can simply select from the collection, but according to documentation, the above 32K limitation should be resolved in 11g.  Thoughts?
    Shane.

    What setting do you use in your report properties - especially in Type and in Region Source?
    If you have Type="SQL Query", then you should have a SELECT statement in the Region Source. Something like: SELECT .... FROM ... WHERE
    According to the ERR-1101 error message, you have probably set Type to "SQL Query (PL/SQL function body returning SQL query)". In this situation APEX expects you to write a body of a PL/SQL function, that will generate the text of a SQL query that APEX should run. So it can be something like:
    declare
    mycond varchar2(4000);
    begin
    if :P1_REPORT_SEARCH is not null THEN
    mycond:='WHERE LAST_NAME like :P1_REPORT_SEARCH ||''%''';
    end if;
    return 'select EMPLOYEE_ID, FIRST_NAME, LAST_NAME from EMPLOYEES ' ||mycond;
    end;
    And for escaping - are you interested in escaping the LIKE wildcards, or the quotes?
    For escaping the wildcards in LIKE function so that when the user enters % you will find a record with % and not all functions, look into the SQL Reference:
    http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14200/conditions007.htm
    (You would than need to change the code of your function accordingly).
    If you are interested in escaping the quotes, try to avoid concatenating the values entered by the user into the SQL. If you can, use bind variables instead - as I have in my example above. If you start concatenating the values into the text of SQL, you are open to SQLInjection - user can enter anything, even things that will break your SQL. If you really need to allow users to choose the operator, I would probably give them a separate combo for operators and a textfield for values, than you could check if the operator is one of the allowed ones and create the condition accordingly - and than still use bind variable for inserting the filtering value into the query.

  • SSRS Error : Query execution failed for dataset 'dataSet'. (rsErrorExecutingCommand) Semantic query execution failed. Invalid object name 'RPT.*********'. (rsSemanticQueryEngineError)

    I am new to SSRS and I am trying to migrate reports from 2008 to 2012. As I have so many reports to migrate, I simply got the back up of ReportServer,
    ReportServerTempDB, and Encryption Key and restored them to test environment. I made necessary configuration from RS configuration tool. I am able to see the reports now when I browse //hostname/reports. But when I open any particular report I am getting some
    error.
    · An error has occurred during report processing.
    (rsProcessingAborted)
    Query execution       failed for dataset 'dataSet'.
          (rsErrorExecutingCommand
    Semantic query        execution failed. Invalid object name
           'RPT. ******'. (rsSemanticQueryEngineError)
    ****** - I am assuming this is a custom data class.
    Does anyone have insight on this? or any better way that I can migrate the reports to new server with less efforts.
    I don’t have the reports solution file to deploy the reports, so I have followed backup and restore process.

    Hi Kishore237,
    According to your description, you migrated some reports from Reporting Services (SSRS) 2008 to 2012. Now you get error when accessing the reports on SSRS 2012. Right?
    In this scenario, did you modify the report data source in database after migration? You can try to open the report in Report Builder or Report designer and check the report dataset. If you can preview the report in Report builder or Report designer,
    please try to redeploy the report to Report Server. If it is still not working, please try to restore the database from backup. And for migrating reports, please follow the "Content-Only Migration" in the link below:
    http://msdn.microsoft.com/en-us/library/ms143724(v=sql.110).aspx
    If you have any question, please feel free to ask.
    Best Regards,
    Simon Hou

  • Query data from MS SQL db through Oracle ? By using JAVA ?

    Hi folks,
    I would like to sync our one table in oracle db with table in different system, stored in MS SQL database.
    What would be the easiest option for connection from Oracle to MS SQL db to be able to query data from MS SQL through some Oracle package?
    If possible, I would like to keep all "tricky steps" within Oracle database. I heard about option with Java, but so far we have no experience with java in Oracle.
    Our database: Oracle 11g Database Standard Edition One
    Many thanks,
    Tomas

    C:\Users\tomeo>dg4pwd HELIOS
    ORACLE Gateway Password Utility
    Constructing password file for Gateway SID HELIOS
    For user account SYSTEM
    OPW-00001: Unable to open password-file (RC=0)
    C:\Users\tomeo>

  • After installed SP1 for SQL Server 2012, can no longer export to csv

    After installing SP1 today via Windows Update, I am no longer able to export data to csv using the SQL Server Import and Export wizard. I get the following error message:
    "Column information for the source and the destination data could not be retrieved, or the data types of source columns were not mapped correctly to those available on the destination provider."
    "Column "col1": Source data type "200" was not found in the data type mapping file."...
    (The above line repeats for each column)
    The work-around I have to do is to manually map each column in the "Edit Mappings..." option from the "Configure Flat File Destination" page of the wizard. This is an extreme inconvenience to have to have to edit the mappings and change
    each column to "string [DT_STR]" type from "byte stream [DT_BYTES]" type each time I want to export to csv. I did not have to do this before installing SP1; it worked perfectly for months with hundreds of exports prior to this update and
    no need to modify mapping.

    I am running Windows 7 64-bit, SQL Server 2012 Express edition. Again, just yesterday from Windows Update, I installed SQL Server 2012 Service Pack 1 (KB2674319), followed by Update Rollup for SQL Server 2012 Service Pack 1 (KB2793634). This situation was
    not occurring before these updates were installed, and I noticed it immediately after they were installed (and of course I restarted my computer after the updates).
    In SSMS I just now created a test DB and table to provide a step-by-step with screenshots.
    Here is the code I ran to create the test DB and table:
    CREATE DATABASE testDB;
    GO
    USE testDB;
    GO
    CREATE TABLE testTable
    id int,
    lname varchar(50),
    fname varchar(50),
    address varchar(50),
    city varchar(50),
    state char(2),
    dob date
    GO
    INSERT INTO testTable VALUES
    (1,'Smith','Bob','123 Main St.','Los Angeles','CA','20080212'),
    (2,'Doe','John','555 Rainbow Ln.','Chicago','IL','19580530'),
    (3,'Jones','Jane','999 Somewhere Pl.','Washington','DC','19651201'),
    (4,'Jackson','George','111 Hello Cir.','Dallas','TX','20010718');
    GO
    SELECT * FROM testTable;
    Results look good:
    id    lname    fname    address    city    state    dob
    1    Smith    Bob    123 Main St.    Los Angeles    CA    2008-02-12
    2    Doe    John    555 Rainbow Ln.    Chicago    IL    1958-05-30
    3    Jones    Jane    999 Somewhere Pl.    Washington    DC    1965-12-01
    4    Jackson    George    111 Hello Cir.    Dallas    TX    2001-07-18
    In Object Explorer, I right-click on the [testDB] database, choose "Tasks", then "Export Data..." and the SQL Server Import and Export Wizard appears. I click Next to leave all settings as-is on the "Choose a Data Source" page, then on the "Choose a Destination"
    page, under the "Destination" drop-down I choose "Flat File Destination" then browse to the desktop and name the file "table_export.csv" then click Next. On the "Specify Table Copy or Query" page I choose "Write a query to specify the data to transfer" then
    click Next. I type the following SQL statement:
    SELECT * FROM testTable;
    When clicking the "Parse" button I get the message "This SQL statement is valid."
    On to the next page, "Configure Flat File Destination" I try leaving the defaults then click Next. This is where I am getting the error message (see screenshot below):
    Then going to the "Edit Mappings..." option on the "Configure Flat File Destination" page, I see that all columns which were defined as varchar in the table are showing as type "byte stream [DT_BYTES]", size "0", the state column which is defined as char(2)
    shows correctly however with type "string [DT_STR]", size "2" (see screenshow below):
    So what I have to do is change the type for the lname, fname, address and city columns to "string [DT_STR]", then I am able to proceed with the export successfully. Again, this just started happening after installing these updates. As you can imagine, this
    is very frustrating, as I do a lot of exports from many tables, with a lot more columns than this test table.
    Thanks for your help.

  • Date formats for SQL statements used by recordset object

    Hi,
    Date formatting appears to be quite problematic for Business One.  I did a forum search for date issues and I don't think I saw any of them with an "answered" status.  I have an issue with formatting a date for the creation of an SQL statement that the DI sends to SQL Server 2005.  I need to format a date so that the localization parameters don't matter for either the client machine or SQL Server's machine.  We don't have a problem as long as our machines are localized as USA.
    I have PL 22 and I have a form - ours - where I use the Today() function to fill a date field.  So this is a date that is not entered by the user.  The result of this function is consistent with the localization parameters on my machine.  We have two other date fields on the form where the user must type in the date. 
    As a test, I changed my machine to the UK parameters.  I then set up the language parameters of Business One for English(United Kingdom).  I changed the date format specifications in Business One so that its format is dd/mm/yy.  I then brought up the form and the field that is formatted by the above function arrived in the form's field as dd/mm/yy.  I then typed in the two other dates in the same format and added the record to the database.  The form's table is user-defined. 
    I dismissed the form then brought it back up loaded with the new record.  The date that was entered by the function appeared in USA format (mm/dd/yy).  The dates that were typed in appeared in the Business One format (dd/mm/yy).  This of course is not consistent.
    When I looked at what got into the database, the formats were the opposite.  Weird!  To make matters really confusing, I run an SQL statement within SQL Server Mgt Studio, and use the WHERE clause to filter on the date that was based on the function.  It didn’t matter what format I used for the WHERE clause, the record came up.  Does anyone have any idea about how I can ensure that I always use the correct date format for SQL statements passed by Business One to SQL Server regardless of where in the world the application is being run?
    Thanks,
    Mike

    Ian,
    Here's what I'm concerned about:  I’m using the date in a “WHERE” clause.
    Assume the date is Aug 3, 2007.
    "SELECT * FROM Table WHERE StartDate > ‘8/3/2007’"
    OR
    "SELECT * FROM Table WHERE StartDate > ‘3/8/2007’"
    If the client machine is set up as USA, the today function will provide the date as formatted in the first query.  If the database server is setup as let’s say the UK, I believe that SQL Server query parser will interpret the date as Mar 8, 2007.
    If the client machine is set up as UK, the today function will provide the date as formatted in the second query.  If the database server is setup as let’s say USA, I believe that SQL Server query parser will also interpret the date as Mar 8, 2007.
    In both cases it would be wrong.
    I know I could use the DATEPART function to get the three parts and this will make the code indifferent to the localization specs of the client machine.  I need to then be able to concatenate those date parts for the “WHERE” clause so that the localization specifications of the database server don’t matter.
    Thanks,
    Mike

Maybe you are looking for