Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove quotes around string using glue_sql() and sub() inside a loop?

My code sample :

fields <- data.frame(names=c("A", "B"))

variables <- c()

for (i in 1:nrow(fields)) {
 
  variables[[i]] <- fields$names[i]
  
  query <- glue_sql("UPDATE schema1.table1 a SET {variables } = (
                      SELECT {variables} FROM schema2.table2 b WHERE b.id_obs = a.id_obs)", .con = pool)

Output:

<SQL> UPDATE schema1.table1 a SET 'A' = (
SELECT 'A' FROM public.test1 b WHERE b.id_obs = a.id_obs)
<SQL> UPDATE schema1.table1 a SET 'B' = (
SELECT 'B' FROM public.test1 b WHERE b.id_obs = a.id_obs)

I’m wondering how can I remove the quotes around my variable_names (A and B) in the output ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to add query <- sub("('.*?')", variables, query) but I don’t really understand the behaviour of sub() within my loop…

Could someone help me out please ?

>Solution :

You can use gsub instead:

query <- gsub("'", '',glue_sql("UPDATE schema1.table1 a SET {variables } = (
                  SELECT {variables} FROM schema2.table2 b WHERE b.id_obs = a.id_obs)", .con = pool) )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading