0% found this document useful (0 votes)
21 views4 pages

Importing and Exporting CSV Files From

Uploaded by

Rui Felix
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views4 pages

Importing and Exporting CSV Files From

Uploaded by

Rui Felix
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Nerds Central: Importing and Exporting CSV Files From SQLServer Using ADODB ...

Page 1 of 4

Partilhar Denunciar abuso Blogue seguinte» Criar blogue Iniciar sessão

Nerds-Central's Quick Post


Blog
Welcome To Nerds-Central If you like it tweet it! Search
Posts 1
• CBL_DIR_SCAN_START
etc tweet
Comments
• Level 78s And Value retweet
Next
• COBOL Search Engine Twitter: @AlexTurner
Shows Organic Growth
• Groups Are Pic X
• The Most Powerful
Feature I Never Knew
Existed

Importing and Exporting CSV Files From SQLServer Using ADODB and
Nerds-Central
VBScript
• The Tsunami Revolution
Podcast - Part Two
• Voice Filtering With Here is a simple pair of scripts to export an SQL Server 2005 table to a csv file and to
Audacity import such a csv file back into SQL Server.
• The Tsunami Revolution
Podcast - End Of The
Personal Computer Today I was faced with a challenge where one of my team members accidentally dropped a table. Restoring the
• MD 686, Retro table structure was no problem because we keep structure scripts, but the data was an issue. We did not want to
Microphone Review - I restore the whole db because it was a development db and was in the middle of being developed upon.
LOVE IT!
• Tips Learnt For However, the table in question was also on another team member's development db, so here are the scripts I
Recording Podcasts came up with the fix the problem. They export the table to a csv file on the Desktop and import the CSV file back
into the repaired database.

The CSV file creation method is very simple. Actually, I think it is too simple because it really does nothing to
take account of non text characters etc. For my table, that was OK; for general use I think some work needs to
Data Export & be done there.
Import Tool
Easy and Fastest Please note that in the reload script I faced two challenges. The first was that the table had an identity column.
way to load data Normally, one cannot set the value of an identity field manually. However, to restore the table values correctly, I
to/from CSV files &
Databases
needed to. The solution was the IDENTITY_INSERT property set (see the code). The second challenge is a bug
www.dbload.com in the ADODB implementation. One of the columns was SQL Variant. Now, "" in the CSV file can be created by
an empty String but is interpreted as NULL. This can be fixed by checking the field value coming from the CSV
derived record set and changing NULL to "". But, due to the bug, "" will not load into the field - arrrrg! The solution
was to substitute a known nonsense String for NULL and then change all instances of that String to '' using an
Compare data of
SQLServer UPDATE SQL statement.
Compare and
Synchronize data Export Script
of SQL Server
quickly
www.devart.com Option Explicit
Dim rs,fieldVals,dbConnIn
Dim connectString,shell,tmp,fso,ts,line
Convert XML to
Excel(XLS) Const adOpenDynamic=2
Shred XML to
Tables. Export to Const adLockPessimistic=2
XLS MDB, CSV. Const adCmdTable=2
Free Trial, US$105 Const adOpenForwardOnly=0
to buy Const adOpenStatic=3
www.novixys.com/Exult
Const adLockReadOnly=1

SQL Scripter ' The connect string should be changed to fit the db in use
Generate T-SQL ' here I am using TCP tp connect to SQL Server 2005
data scripts, connectString="Provider=SQLNCLI;Server=127.0.0.1;Database=dv;Uid=*****;Pwd=*****;"
Export to Set dBConnIn = CreateObject("ADODB.Connection")
CSV/Text, PDF,
Excel, CSV to SQL dBConnIn.Open connectString
www.sqlscripter.com ' This is just a simple way of getting a record set from and SQL Query
Set rs=CreateObject("ADODB.RecordSet")
rs.Open _
Followers
"T_MchnPrps", _
dbConnIn, _
Follow adOpenStatic, _
with Google Friend Connect
adLockReadOnly, _
Followers (5) adCmdTable

Set shell=CreateObject("WScript.Shell")
Set fso=CreateObject("Scripting.FileSystemObject")
Set ts=fso.OpenTextFile(shell.SpecialFolders("Desktop") & "\" & "T_MchnPrps.csv",2,T
line=""
Already a member?Sign in For Each tmp In rs.Fields
line=line & tmp.Name & ","
Dr Alexander J Turner Next
ts.WriteLine Left(line,Len(line)-1)
While Not rs.EOF
line=""
For Each tmp In rs.Fields
line=line & """" & Replace(tmp.Value,"""","""""") & ""","
Next
ts.WriteLine Left(line,Len(line)-1)
rs.MoveNext
Wend

About Me rs.Close
ts.close

http://nerds-central.blogspot.com/2008/01/importing-and-exporting-csv-files-from.html 25-10-2010
Nerds Central: Importing and Exporting CSV Files From SQLServer Using ADODB ... Page 2 of 4

Part of the csv file

MchnId,Sequ,Type,Data,Prnt
"1","1","1","RBSManuf0","1"
"1","2","2","IBM T42","1"
"1","3","3","RBSSerl0","1"
"2","4","1","RBSManuf1","1"
"2","5","2","IBM T42","1"
"2","6","3","RBSSerl1","1"
"3","7","1","RBSManuf2","1"
"3","8","2","Dell PP04S ","1"
"3","9","3","RBSSerl2","1"
"4","10","1","RBSManuf3","1"
"4","11","2","","1"
"4","12","3","RBSSerl3","1"
"5","13","1","RBSManuf4","1"

Import Script

Option Explicit
Dim rsOut,rsIn,dbConnOut,fieldVals,dbConnIn,i
Dim connectString,shell,tmp,fso,ts,line,fieldPost,fieldValues

Const adOpenDynamic=2
Const adLockPessimistic=2
Const adCmdTable=2
Const adOpenForwardOnly=0
Const adOpenStatic=3
Const adLockReadOnly=1

' The connect string should be changed to fit the db in use


' here I am using TCP tp connect to SQL Server 2005
connectString="Provider=SQLNCLI;Server=127.0.0.1;Database=dv;Uid=*****;Pwd=*****;"
Set dBConnOut = CreateObject("ADODB.Connection")
dBConnOut.Open connectString
dbConnOut.Execute "DELETE FROM T_MchnPrps"
dbConnOut.Execute "SET IDENTITY_INSERT T_MchnPrps ON"

Set rsOut=CreateObject("ADODB.RecordSet")
rsOut.Open _
"T_MchnPrps", _
dbConnOut, _
adOpenDynamic, _
adLockPessimistic, _
adCmdTable

Set shell=CreateObject("WScript.Shell")

Set dBConnIn = CreateObject("ADODB.Connection")


dbConnIn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & shell.SpecialFolders("Desktop") & ";" & _
"Extended Properties=""text;FMT=Delimited;HDR=yes"";"

Set rsIn=CreateObject("ADODB.RecordSet")
rsIn.Open _
"T_MchnPrps.csv", _
dbConnIn, _
adOpenStatic, _
adLockReadOnly, _
adCmdTable

Redim fieldPos(rsIn.Fields.Count-1)
Redim fieldValues(rsIn.Fields.Count-1)
i=0
For i=0 To rsIn.Fields.Count-1
fieldPos(i)=i
Next

While Not rsIn.EOF


For i=0 To rsIn.Fields.Count-1
fieldValues(i)=rsIn.fields(i).Value
If IsNull(fieldValues(i)) Then fieldValues(i)="-#%REMOVE%#-"
Next
rsOut.AddNew fieldPos,fieldValues
rsIn.MoveNext
Wend

rsIn.Close
rsOut.Close
dbConnOut.Execute "UPDATE T_MchnPrps SET Data='' WHERE Data='-#%REMOVE%#-'"
dbConnOut.Execute "SET IDENTITY_INSERT T_MchnPrps OFF"
WScript.Echo "Import Complete"

http://nerds-central.blogspot.com/2008/01/importing-and-exporting-csv-files-from.html 25-10-2010
Nerds Central: Importing and Exporting CSV Files From SQLServer Using ADODB ... Page 3 of 4

3 comments:

Anonymous said...

works well with a view too

12:26 PM

Alex Turner said...

thanks for the feedback :)

12:29 PM

Anonymous said...

Although if you use a view, views don't sort, even though they look like they should, so you have to sort the view
once you have the view results back.

You also need to connect to the database slightly differently.

'CONNECT TO DATABASE
set oConn = CreateObject("ADODB.Connection")
oConn.Open "your connection goes here"
set rs = CreateObject("ADODB.Recordset")
rs.ActiveConnection = oConn

dim strsql
strsql = "select * from vwMyView order ID ASC"

rs.Source = strsql
rs.open()

Set shell=CreateObject("WScript.Shell")
etc. as before

12:40 PM

Post a Comment

Please feel free to leave comments or thoughts.

Comment as: Select profile...

Post Comment Preview

Newer Post Older Post Home

Subscribe to: Post Comments (Atom)

http://nerds-central.blogspot.com/2008/01/importing-and-exporting-csv-files-from.html 25-10-2010
Nerds Central: Importing and Exporting CSV Files From SQLServer Using ADODB ... Page 4 of 4

Recent Comments Blog Archive


► 2010 (116)
Alex Turner wrote...
The type keyword make the compiler resolve the following token as a type ► 2009 (109)
name rather than a COBOL reserved word or data item. So:invoke type x::yis ▼ 2008 (125)
the same invoke "x"::"y" ► December (6)
Robert Collins wrote... ► November (5)
Can you elaborate on what changes you made to the method you are ► October (1)
invoking?I'm still not clear on why you have to specify Type when ► September (12)
invoking a method.Thanks!
► August (7)
mensajes claro wrote... ► July (11)
Great post, well written and very useful. Thank you.
► June (11)
Windows Phone 7 Application Development wrote... ► May (30)
Thanks for the nice information.This will help a lot of users. ► April (11)
Anonymous wrote... ► March (10)
My comment didn't work the first time. Here goes.The listing you ► February (4)
provide is not vbscript, but VBA.Could you kindly teach how to actually ▼ January (17)
manipulate borders using vbscript?I have failed after...
Continue >> Beware 'ultra-fast' databases (re: SQLite)
What Technology Should I Know/Use As A Developer
Anonymous wrote... Importing and Exporting CSV Files From SQLServer U...
' Set objRange2 = objWorksheet2.Range("A10") '
objRange2.Copy 'objExcel2.Range("B10:E17").Select Using Excel As A Web Service Client
'objWorksheet2.PasteSpecial Paste =xlPasteFormats ... Excel Filter Report Scripting Macro
Continue >> Scripting Macro Forum's First Post
Generic Viagra wrote... Processing MOV Files On Ubunutu Linux
First of all, I want to send a salute to every reader and writer of this Wow What A COOL Robot
magnificent column. After this, I want to share with you my passion that is fed Announcing Excel Scripting Macro Forums
by all those beautiful landscapes. The fact of...
Continue >> UAT Criteria, An R.A.D. Approach To User Acceptanc...
Bart's Amazing Picture
Alex Turner wrote... Motion Compensation For The Bourne Ultimatum
I'll have a poke around. But... I never got much further than the first
chapter on the book - maybe one day I should finish it! Excel & VBScript Index Page
Global Policing - The New Military Role?
Alex Turner wrote... My Lulu Page
If you are wanting to do this using a script the solution is to open to separate
XL workbooks off the same XL COM object and then write a loop which takes Sexiest Geek?
the values of the cells and compares... About Me
Continue >>
► 2007 (200)
Anonymous wrote... ► 2006 (16)
Great Post, ThanksHi,How can we compare excel sheet with another excel
sheet when the cells in both the sheets are in different cells. I want to
compare A1 in one sheet to L2 in another sheet (Like...
Continue >>

http://nerds-central.blogspot.com/2008/01/importing-and-exporting-csv-files-from.html 25-10-2010

You might also like