Export data to CSV in SQL Server

Hi,
I am trying to write a Java JDBC program exporting data
from the database into CSV file using SQL Server 2005 DB.
From that query:
String="SELECT * into OUTFILE '"+filename+'" FIELDS TERMINATED BY ',' FROM table1";
getting: "SQLException: Incorrect syntax near 'myfilename.csv'
Yes, I put filename in single quotes. Same problem without them, but it strips out csv file extension.
Using JTDS driver 1.2.4 on WinXP.
Will later need to insert that into a batch process.
What is a reason for that error? - I saw many many posts on the net, but no good explanations so far.
So how do I fix that ?
Is there a better way of doing it in SQL server ?
I am a Java developer, not a DBA or Unix Sys Admin ;-)
Please help !
TIA,
Oleg.

Here is one way to do it in Java. You can customize as you like. Do a Google on how to get a DataSource (or DriverManager) connection for SqlServer. If you do not know how to get a PrintWriter, you do something like:
PrintWriter writer = new PrintWriter(new FileOutputStream('results.csv");This will generate a generic CSV. It is probably not ideal, but should get you started.
    public final void serialize(final DataSource ds, final String sql, final PrintWriter writer)
        throws SQLException {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet results = null;
        try {
            conn = ds.getConnection();
            stmt = conn.prepareStatement(sql);
            results = stmt.executeQuery();
            ResultSetMetaData meta = results.getMetaData();
            int columnCount = meta.getColumnCount();
            while (results.next()) {
                for (int current = 0; current < columnCount; current++) {
                    Object value = results.getObject(current + 1);
                    if (current > 0) {
                        writer.print(", ");
                    writer.print("\"" + (value == null ? "" : value.toString()) + "\"");
                writer.println();
            writer.flush();
        finally {
            if (results != null) {
                try {
                    results.close();
                catch (SQLException e) {
                    e.printStackTrace();
            if (stmt != null) {
                try {
                    stmt.close();
                catch (SQLException e) {
                    e.printStackTrace();
            if (conn != null) {
                try {
                    conn.close();
                catch (SQLException e) {
                    e.printStackTrace();
    }My advice is to use BCP to start. The docs for the tool are here: [http://msdn.microsoft.com/en-us/library/aa174646(SQL.80).aspx]. You can manipulate the results in Access or Excel if you need to. Since it seems you are being thrown into an emergency and getting it fast is more important than you spending months learning additional Java API's.
- Saish

Similar Messages

  • SQL Developer 2.1.0.63 - Export Data menu missing for SQL Server databases

    Hi
    The Export Data menu only appears for Oracle databases in this version, it does not appear for SQL server databases.
    To demonstrate:
    Press F9 to run query
    Right click on Query Result data
    For Oracle an Export Data sub menu appears
    For SQL server no Export Data sub menu appears
    This worked in previous versions.
    Is this functionality going to reappear?
    Thanks
    Dave

    Hi,
    Looks like this is exactly the same problem for third party connections as I have the exact same issue for mySQL.
    I had to apply 1.5.5 version to fix it.
    Hope we're going to have this solved !
    Thanks,
    JP

  • Pulling data from oracle into sql server 2005

    hi,
    these days i am working on sql server 2005 on windows server 2008 64 bit.
    and oracle 10g on 32 bit unix.
    my problem is that when i am pulling data from oracle into sql server it shows me about *500-700 entries less*.
    why this is happening? is it because 32 bit to 64bit? or is it because of different os?

    Akki,
    are you using snapshot or replication from MSSQL? I am doing the same thing, hope to share your experience.
    I am using import/export from MGT studio and pull some data from Oracle database, I am working on how to update the changes on these tables pulled from Oracle.
    Thanks,
    -hank

  • Export tables form Oracle8 to SQL Server 7.0

    Hello
    I use Dts (data transformation service) to export tables/data form Oracle8 to SQL Server 7.0. It seems to work fine, but somehow escape charecters like carrige return and spaces,are presented as a '' sign in SQL Server. How can I avoid this during the export of data from Oracle.(I do want to use a trigger to remove them afterwards !)Please help
    Regards Ivan

    CORRECTION !
    Bottom line should read:
    (I do NOT want to use a trigger to remove them afterwards !)
    Ivan
    <BLOCKQUOTE><font size="1" face="Verdana, Arial, Helvetica">quote:</font><HR>Originally posted by Ivan Posselt ([email protected]):
    Hello
    I use Dts (data transformation service) to export tables/data form Oracle8 to SQL Server 7.0. It seems to work fine, but somehow escape charecters like carrige return and spaces,are presented as a '' sign in SQL Server. How can I avoid this during the export of data from Oracle.(I do want to use a trigger to remove them afterwards !)Please help
    Regards Ivan<HR></BLOCKQUOTE>
    null

  • Can not extract data into BW from SQL SERVER

    Dear All,
      I meet a problem to extract data from database(MS SQL Server 2000(sp3)) into BW now and can not extract data into BW ODS, even PSA, In the monitor, display yellow light(0 from 0 record), detail message just display message "data request arranged" "confirmed with: confirmation" in requests(message) step; "missing message: request received" in extract (message)  step; "no data" in processing(data packet) step and so on. but in fact, there are two records in my database test table and DB connection is OK. Even I can extract data from another test oracle database into BW ODS successfully.
       Our BW system has two BW applicaton server and use oracle database. the one application server locates on IBM AIX host. the another one locates on one NT server. the application server on NT server is used for data extration from MS SQL SERVER  database into BW oracle database. and MS SQL SERVER and NT platform application server locate on same one host. DBSL was installed on the NT application server already. and DB connector also was created successfully for MS SQL SERVER and datasource also was generated. DBSL type is Kernel640-WIN-IA32bit-unicode. my BW system is ECC5.0/UNICODE/ORACLE. all table/view/field name of MS SQL server is upcase and have not any specific character. for example: ZDEMO etc.
    wait your help.
    Thanks in advance.
    Billy

    Hi  Ravi,
    Could you help me to get knowledge about the followings:
    approximately how many records    extracting and transfering  from SAP R/3 to BIW  in an organisation. for that how much time  will take .
    How to extract data from  two are three source system  to BIW. Kindly help me with step by step explanation .If any screen shots with documents pls fwd to my ID. "[email protected]"
    Your help highly appreciated.
    Thanks.
    Hema

  • Date column in OBIEE-SQL Server

    Hi expert,
    I have created date (datetime)column in sql server cube. Now I wat it inmy OBIEE as date. how to do that.
    When we import,there are only three option->Double,Varchar,Unknown.

    Something wrong.... once you import table in rpd the column should have Type as DATETIME or DATE.
    If its not the case then you can change the format in rpd.
    If helps pls mark

  • Data Source for MS SQL SERVER

    Need Help on how to add a data source from MS SQL Server. Please give an example using PUB as the database and the server is N12345\SQLSERVER. Thanks.

    Connecting to SQL 2000 server worked very easily. Make sure you start the SQL Server and the Sun Java Studio Creator IDE. In the Server Navigator pane, right click on the 'Data Sources' node and pick up the menu item' Add Source'. This brings up a dialogue box wherein you need to insert info regarding the hostname, password, database information etc. For a detailed screen shots of this you see my page at
    http://www.mysorian.com/htek. The last item in the scrolling page is the one you should look for.

  • Does xcelsius access data model in MS sql server 2000

    have the following scenario: I need to create a dashboard which will be accessed through a Microsoft Office SharePoint server portal. This dashboard will be used for analysis of Agencies and Underwriters; they should be able to drill down to policy level details. 
    The data will originate from a Data Warehouse (Relational Schema) which resides on a Microsoft SQL server 2000 platform.
    Q) Does Xcelsius work off a relational model or does the data model need to be converted to a Dimensional Star schema?  Do you have to create Cubes?
    A)
    Q) It was mentioned in the book that Xcelsius can connect to a Microsoft SharePoint server using web part, however there is no information in the help menu to do that task? 
    A)
    My thought) I was also thinking that the data model build on MS SQL SERVER 2000 can be used to create a Universe, which then can link to Live Office using Query as a Web Service (QAAWS) and used to build Xcelsius model.  (Does one have to go this route, or can one access the data model created on SQL SERVER 2000?)
    Any Feedback)

    I need to create a dashboard which will be accessed through a Microsoft Office SharePoint server portal. This dashboard will be used for analysis of Agencies and Underwriters; they should be able to drill down to policy level details.
    The data will originate from a Data Warehouse (Relational Schema) which resides on a Microsoft SQL server 2000 platform.
    Q) Does Xcelsius work off a relational model or does the data model need to be converted to a Dimensional Star schema? Do you have to create Cubes?
    A) Xcelsius works on an X/Y (Column/Row) table model, strictly based on the Excel structure.  Though the underlying data model is a table, it is not inherently relational as it does not impose any BC Normal Form requirements.
    Xcelsius works primarily with data embedded in an integrated Excel workbook.  Data can be input to the workbook by a variety of methods, from importing a premade Excel workbook into the the model to retrieving data from flat files (.txt, .xml, .etc) to getting data from a connection such as a WebService. 
    There is no capability to connect directly, 1:1, to a database source and execute SQL queries.  An intermediary is required to retrieve data from a database, such as a WebService or an XML Data connection.

  • How to insert data from access to sql server ?

    How to insert data from access to sql server ?
    Please help me
    thanks

    phamtrungkien wrote:
    How to insert data from access to sql server by JAVA?The first four words of my last post:
    masijade wrote:
    JDBC with two connectionsGet a resultset from the jdbc-odbc bridge access connection, cycle through it and add batch insert commands to the jdbc connection to sql server. Give it a try and if the code has an error, then post your code ans ask a question.
    The real question, though, is why you think it absolutely necessary to use Java for this.

  • Fetch data from another mirosoft sql server to sap

    Dear all,
                   I want to fetch data from another mirosoft sql server
                    to SAP(my sap server IN unix, oracle 10g).
    Thanks
    Shashi
    Moderator Message: Try to do you own research before posting your question. Get back to the forums in case you are stuck with any issue
    Edited by: Suhas Saha on Jul 26, 2011 3:21 PM

    hi,
    u should see following documentation:
    Oracle9i Heterogeneous Connectivity Administrator's Guide
    Release 1 (9.0.1)
    Part Number A88789_01
    in it u just go to chapter no. 4 (using the gateway),,u'll find ur answer there.
    regards
    umar

  • Import data from csv to SQL database

    How to  Import data from csv to SQL database through BLS-xMII?

    Hi,
    if you using Oracle, you may also use the bulk insert with MII. You can use the String List to XML parser to convert your CSV to XML, and then use a query that calls a stored procedure which does the bulk insert.
    Also have a look at thread [read XML file into stored procedure|http://forums.sdn.sap.com/click.jspa?searchID=63850236&messageID=7455643].
    Michael

  • System.Data.SqlClient.SqlException (0x80131904): SQL Server detected a logical consistency-based I/O error: incorrect checksum

    Hello,
    I am migrating client's database to my hosted environment, the client runs
    SQL Server 2008 R2, and we run SQL Server 2014.
    I am stuck on restoring one log file, which left below error message when I restore it:
    Restoring files
      DBFile_20150401030954.trn
    Error Message: System.Data.SqlClient.SqlException (0x80131904): SQL Server detec
    ted a logical consistency-based I/O error: incorrect checksum (expected: 0x512cb
    ec3; actual: 0x512dbec3). It occurred during a read of page (1:827731)
    in databa
    se ID 49 at offset 0x000001942a6000 in file 'F:\MSSQL12.INSTANCE9\MSSQL\Data\Ody
    sseyTSIAKL_Data.mdf'.  Additional messages in the SQL Server error log or system
     event log may provide more detail. This is a severe error condition that threat
    ens database integrity and must be corrected immediately. Complete a full databa
    se consistency check (DBCC CHECKDB). This error can be caused by many factors; f
    or more information, see SQL Server Books Online.
    RESTORE LOG is terminating abnormally.
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolea
    n breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception
    , Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObj
    ect stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand
     cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler,
    TdsParserStateObject stateObj, Boolean& dataReady)
       at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
       at System.Data.SqlClient.SqlDataReader.get_MetaData()
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, Run
    Behavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBe
    havior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 time
    out, Task& task, Boolean asyncWrite, SqlDataReader ds)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehav
    ior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletio
    nSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehav
    ior, RunBehavior runBehavior, Boolean returnStream, String method)
       at System.Data.SqlClient.SqlCommand.ExecuteScalar()
       at OnBoardingTrnRestore.FileRestorer.FileIsRestored(SqlConnection connection,
     String sourceBackupFileName, String sourceDatabaseName, String destinationDatab
    aseName, String databaseName, String strFileName) in c:\Dev\WiseCloud\OnBoarding
    TrnRestore\OnBoardingTrnRestore\FileRestorer.cs:line 223
    ClientConnectionId:6f583f98-9c23-4936-af45-0d7e9a9949ea
    Finished
    I have run restore filelistonly and verifyonly in both client and my box, and both worked well:
    XXX_Data D:\Program Files (x86)\XXX\Data\YYY_Data.mdf
    restore filelistonly:
    D PRIMARY
    70922469376 35184372080640
    1 0
    0 00000000-0000-0000-0000-000000000000
    0 0
    0 512 1
    NULL 279441000014839500242
    66CC6D17-575C-41E5-BB58-3FB4D33E288C
    0 1 NULL
    XXX_Log E:\Program Files (x86)\XXX\Log\YYY_Log.ldf
    L NULL
    31985762304 35184372080640
    2 0
    0 00000000-0000-0000-0000-000000000000
    0 0
    0 512 0
    NULL 0
    00000000-0000-0000-0000-000000000000 0
    1 NULL
    restore verifyonly:
    Attempting to restore this backup may encounter storage space problems. Subsequent messages will provide details.
    The path specified by "D:\Program Files (x86)\XXX\Data\YYY_Data.mdf" is not in a valid directory.
    Directory lookup for the file "E:\Program Files (x86)\XXX\Log\YYY_Log.ldf" failed with the operating system error 3(The system cannot find the path specified.).
    The backup set on file 1 is valid.
    Dbcc checkdb also confirmed there is no error in client sql server database.
    dbcc checkdb (XXX, NOINDEX) 
    Results as follows:
    DBCC results for 'XXX'.
    Warning: NO_INDEX option of checkdb being used. Checks on non-system indexes will be skipped.
    Service Broker Msg 9675, State 1: Message Types analyzed: 17.
    Service Broker Msg 9676, State 1: Service Contracts analyzed: 9.
    Service Broker Msg 9667, State 1: Services analyzed: 7.
    Service Broker Msg 9668, State 1: Service Queues analyzed: 7.
    Service Broker Msg 9669, State 1: Conversation Endpoints analyzed: 0.
    Service Broker Msg 9674, State 1: Conversation Groups analyzed: 0.
    Service Broker Msg 9670, State 1: Remote Service Bindings analyzed: 0.
    Service Broker Msg 9605, State 1: Conversation Priorities analyzed: 0.
    DBCC results for 'sys.sysrscols'.
    There are 23808 rows in 350 pages for object "sys.sysrscols".
    DBCC results for 'BMBoard'.
    There are 0 rows in 0 pages for object "BMBoard".
    DBCC results for 'CusOutturnHeader'.
    There are 0 rows in 0 pages for object "CusOutturnHeader".
    CHECKDB found 0 allocation errors and 0 consistency errors in database 'XXX'.
    DBCC execution completed. If DBCC printed error messages, contact your system administrator.
    We use ftp to transfer the log files from the another country to here, I confirmed the file's MD5(checksum) is same as the copy in client's environment, we have tried to upload the file a couple of times, same outcome.
    The full backup is fine, I have successfully restored a series log backups prior to this file.
    Has anyone seen this issue before? It is strange, all information indicates the file is good,but somehow it goes wrong.
    Below are the version details:
    Client: 
    MICROSOFT SQL SERVER 2008 R2 (SP2) - 10.50.4000.0 (X64) 
    My environment:
    Microsoft SQL Server 2014 - 12.0.2480.0 (X64) 
    Jan 28 2015 18:53:20 
    Copyright (c) Microsoft Corporation
    Enterprise Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: )
    Thanks,
    Albert

    Error Message: System.Data.SqlClient.SqlException (0x80131904): SQL Server detec
    ted a logical consistency-based I/O error: incorrect checksum (expected: 0x512cb
    ec3; actual: 0x512dbec3). It occurred during a read of page (1:827731)
    in databa
    se ID 49 at offset 0x000001942a6000 in file 'F:\MSSQL12.INSTANCE9\MSSQL\Data\Ody
    sseyTSIAKL_Data.mdf'.  Additional messages in the SQL Server error log or system
     event log may provide more detail. This is a severe error condition that threat
    ens database integrity and must be corrected immediately.
    Hi Albert,
    The above error message usually indicates that there is a problem with underlying storage system or the hardware or a driver that is in the path of the I/O request. You can encounter this error when there are inconsistencies in the file system or if the database
    file is damaged.
    Besides other suggestions, consider to use the
    SQLIOSim utility to find out if these errors can be reproduced outside of regular SQL Server I/O requests and change
    your databases to use the PAGE_VERIFY CHECKSUM option.
    Reference:
    http://support.microsoft.com/en-us/kb/2015756
    https://msdn.microsoft.com/en-us/library/aa337274.aspx?f=255&MSPPError=-2147217396
    Thanks,
    Lydia Zhang
    Lydia Zhang
    TechNet Community Support

  • Mapping between oracle data types and ms sql server data types

    hello
    i need mapping between oracle data types and ms sql server data types
    where can i find them ?

    read this
    http://download.oracle.com/docs/cd/E10405_01/doc/appdev.120/e10379/ss_oracle_compared.htm

  • Inserting data from Oracle to SQL Server 2008

    Hi All,
    I am using oracle 9.2.0.7 and SQL server 2008 in windows server 2003 operating system.
    My requirment is like below.
    1) I would liek to insert data from the Oracle database to SQL Server.
    For the above requirement we have created the ODBC, then configure the listener file, tns file, and created the db link. This part is working fine as I am able to select the data from the SQL Server.
    But when I am inserting the record from the oracle database to the SQL Server I am getting the error, (ORA-00904) Here oracle can not identified the column name.
    My insert statement is like below.
    insert into test@SQLTEST (name, fullname)
    values ('Oracle', 'Oracle server data');
    Test is the SQL server table name and sqltest is the db link name.
    If I am select the data
    select * from test@SQLTEST from Oralce I am getting the data properly.
    Thanks,
    SUN
    Edited by: User SUN@ on Jun 9, 2010 5:49 PM

    Hi,
    I modify the column name as "f_name" and "l_name";
    Still I am getting the same error;
    Thanks,
    SUN

  • Inserting Data from Oracle to SQL Server on the Real Time Basis.

    Hi Everyone,
    I need to insert data from Oracle to SQL Server on the Real Time basis, we have to fetch data from oracle approx 20 tables, and each table has more than 30 Fields. I need to fetch data in every 15 mins.
    I have created a job using SQL SERVER Agent by writing insert queries for all the tables with conditions that no rows will be inserted which is already in SQL. note that this job is taking only 1 min to execute.
    But in this way our SQL Server getting hanged and it giving problems to other application running in the SQL SERVER.
    So i m requesting all of you that what is the best way to insert huge amount of data on the real time basis.
    Thanx in Advance.

    1) Create Linked server 
    2) insert data using openquery  and set job in sql agent
    3) run job after 15 minutes

Maybe you are looking for

  • I am trying to capture from Sony HDV 1080i VTR FCP giving an error of not able to initialize

    i am trying to capture from Sony HDV 1080i VTR FCP giving an error of not able to initialize. I am not able to capture the content in DV mode. i am using a Firewire 800 to 400 converter and a 6 pin firewire cable to connect to the SonyHDV VTR. Please

  • Data from query to excel

    I'm using SQL to query a database which works fine. Then I want to pass it to excel from within Labview. So intially I just have it reading row by row, column by column to take in data. Well this can take forever with a lot of info from the database.

  • Looking for a case!

    Hey everybody, I'm looking for an iPhone 5 case, preferably dual layer and even a little thick (I like thicker cases for some reason ). I've tried the OtterBox Commuter but I don't like how the Apple logo is exposed. I have the Defender, but obviousl

  • WRT54G & Comcast - Operating more than one wireless PC at the same time

    First, I want to thank the many advisors and experts that contribute so freely to this knowledge base.  I have read the many insights into Comcast/cable modems.  Because to that I am able to connect one (1) laptop via wireless to my WRT54G which is a

  • Converting CLOB to BLOB at once

    Hello all! I have to convert CLOB to BLOB in my application. My CLOB contains XML document built with dbms_xmldom, an I need to put it into column of type BLOB. Knowing several ways to do it, I'm searching for the best one. So I considered the folowi