Article
· Aug 29 1m read

How to programmatically read a CSV file line by line

InterSystems FAQ rubric

This can be achieved by using the CSV() procedure of the %SQL.Util.Procedures class.
Below is an example of usage code. (Assuming that the file test.csv is in c:\temp.)

 Set rowtype="Name VARCHAR(50),UID VARCHAR(50), PHONE VARCHAR(50)"
 Set filename="c:\temp\test.csv"
 Set result=##class(%SQL.Statement).%ExecDirect(,"call %SQL_Util.CSV(,?,?)",.rowtype,.filename)
 Set rset =result.%NextResult()
 
 // To display all results, use do rset.%Display()
 While rset.%Next() {
     Write "Name:",rset.%GetData(1)," UID:",rset.%GetData(2)," PHONE:",rset.%GetData(3),!
     }

 Set rset="",result=""
 Quit

By executing the above, you can access each row and field as a result set. Example execution:

USER>do ^CSV
Name    UID     PHONE
aaa     0001    080-1111-1111
bbb     0003    090-2222-2222
ccc     0009    050-3333-3333
ddd     0010    0120-17-1972
4 Rows(s) Affected

Please also see the class reference for the %SQL.Util.Procedures class.
Class reference:%SQL.Util.Procedures.CSV()

Discussion (2)3
Log in or sign up to continue