How to use dynamic values while executing SQL scripts in R

后端 未结 2 937
执笔经年
执笔经年 2021-01-15 03:52

My R workflow now involves dealing with a lot of queries (RPostgreSQL library). I really want to make code easy to maintain and manage in the future.

I

相关标签:
2条回答
  • 2021-01-15 04:32

    sqlInterpolate() is for substituting values only, not other components like table names. You could use other templating frameworks such as brew or whisker.

    0 讨论(0)
  • 2021-01-15 04:37

    In ?DBI::SQL, you can read:

    By default, any user supplied input to a query should be escaped using either dbQuoteIdentifier() or dbQuoteString() depending on whether it refers to a table or variable name, or is a literal string.

    Also, on this page:

    You may also need dbQuoteIdentifier() if you are creating tables or relying on user input to choose which column to filter on.

    So you can use:

    sqlInterpolate(ANSI(), 
                   "SELECT count(*) FROM ?my_table", 
                   my_table = dbQuoteIdentifier(ANSI(), "table_name"))
    # <SQL> SELECT count(*) FROM "table_name"
    
    0 讨论(0)
提交回复
热议问题