Simple Coldfusion/SQL Server Upload Script
SQL Server , ColdFusion - Author:Steve Weyrick at 2:47 PM Add commentsI found this script while browsing the other day. I thought it might be useful for anyone needs to upload data into SQL Server from a csv file. The only catch is that you can't have NULL values in your CSV file.
<cffile action="read" file="\\stg-wb-20\ims-STG-WB-20\testSteve\ss.csv" variable="csvfile">
<!--- loop through the CSV-TXT file on line breaks and insert into database --->
<cfloop index="index" list="#csvfile#" delimiters="#chr(10)##chr(13)#">
<cfquery name="importcsv" datasource="dsnDB1">
INSERT INTO tblCycleCountData (ctCampus,ctDate,ctAISLE,ctLOCATION,ctITEM,ctLPID,ctQTY,_
ctZONE,ctLOCTYPE,ctLPIDPRESENT,ctCOUNTTOTAL)
VALUES
('#listgetAt('#index#',1, ',')#',
'#listgetAt('#index#',2, ',')#',
'#listgetAt('#index#',3, ',')#',
'#listgetAt('#index#',4, ',')#',
'#listgetAt('#index#',5, ',')#',
'#listgetAt('#index#',6, ',')#',
'#listgetAt('#index#',7, ',')#',
'#listgetAt('#index#',8, ',')#',
'#listgetAt('#index#',9, ',')#',
'#listgetAt('#index#',10, ',')#',
'#listgetAt('#index#',11)#')
</cfquery>
</cfloop>
<!--- use a simple database query to check the results of the import - dumping query to screen --->
<cfoutput>Done</cfoutput>






Oct 16, 2008 at 3:45 PM If you're running CF8, there are better ways to loop over a file line by line. CF8 supports the FILE attribute of CFLOOP.
Oct 16, 2008 at 4:19 PM Thanks for your input Michael. I have only been using Coldfusion 8 for about a month, so I am pretty green. Next time I have to do something like this, I will definitely use your methodology.
Oct 16, 2008 at 5:58 PM If you know you will be using SQL Server, then you might also look into BULK INSERT: http://blog.sqlauthority.com/2008/02/06/sql-server-import-csv-file-into-sql-server-using-bulk-insert-load-comma-delimited-file-into-sql-server/
Oct 16, 2008 at 9:38 PM Hey, some good stuff here that I wasn't aware of myself... I did want to point out very briefly that the script has some extra characters '#listgetAt('#index#',1, ',')#' could be '#listgetAt(index,1, ',')#' Personally I think the latter with fewer quotes and pounds is a bit more legible. Of course your mileage may vary. :)
Oct 17, 2008 at 8:27 AM Also.. instead of having your loop setup like this