Query result save to csv
Query result save to csv
Discussion (6)0
Comments
This code will output arbitrary query to CSV.
/// w $System.Status.GetErrorText(##class(!!!).ToCSV())
ClassMethod ToCSV(file = {##class(%File).NormalizeDirectory(##class(%SYS.System).TempDirectory())_ "out"}, query As %String = "SELECT 1,2,'a'", args...) As %Status
{
#dim sc As %Status = $$$OK
// Cant't do $zcvt($e(file,*-4,*), "l") as it can bring unexpected effect on case-sensitive fs
// Possible solution is to make file byref but it should be done in application code
set:$e(file,*-4,*)=".csv" file = $e(file, 1, *-4)
set dir = ##class(%File).GetDirectory(file)
set exists = ##class(%File).DirectoryExists(dir)
if (exists=$$$NO) {
set success = ##class(%File).CreateDirectoryChain(dir, .code)
set:success=$$$NO sc = $$$ERROR($$$GeneralError, "Unable to create directory: '" _ dir _ "', reason: " _ code)
}
quit:$$$ISERR(sc) sc
#dim rs As %SQL.StatementResult
set rs = ##class(%SQL.Statement).%ExecDirect(,query, args...)
if rs.%SQLCODE=0 {
do rs.%DisplayFormatted("CSV", file)
} else {
set sc = $$$ERROR($$$SQLError, rs.%SQLCODE, rs.%Message)
}
quit sc
}Fantastic, @Eduard Lebedyuk!
Do you want to create a ZPM module from it?
Included it into csvgen module.
to export SQL to CSV you can do the following:
USER>set query="select * from your.classname"
USER>w ##class(community.csvgen).SQLToCSV(";",1,"/folder/file.csv",query)How to encorporate this code to the service or business process to query Oracle database?
There are two options:
- Use SQL Gateway to create Linked Tabled from Oracle (if there are a lot of tables it might be better to create a linkage with a view). After that query Linked Table same as any normal InterSystems IRIS table using the code snippet above.
- Write a service with the EnsLib.SQL.InboundAdapter to query Oracle database. In that case you need to implement a CSV writer.
OK, thanks