select max(f) from (with t as ( select format( 'COPY (SELECT cast(s.operativen_prot as bytea) FROM migration.mssql_patient_dosie_data s where s.dep_patient_id = %s) TO ''%s''', f.dep_patient_id, concat('/archive/ss-storage/Protocol2/', f.dep_patient_id, '.hex')) as query from migration.mssql_patient_dosie_data f where f.operativen_prot is not null ) select f_execute_test(query) f from t) as t ;