【问题标题】:Converting a Table into SQL Statements将表转换为 SQL 语句
【发布时间】:2022-07-22 01:26:34
【问题描述】:

我在 R 中有这个数据集:

my_table = data.frame(id = c(1,2,3), name = c("sam", "smith", "sean"), height = c(156, 175, 191), address = c("123 first street", "234 second street", "345 third street"))

  id  name height           address
1  1   sam    156  123 first street
2  2 smith    175 234 second street
3  3  sean    191  345 third street

基于此表,我正在尝试生成以下字符串语句 - 从“my_table”中获取条目并将它们放入以下格式::

# pretend some table called "new_table" already exists - below is the desired output that I want:

INSERT INTO new_table ( id, name, height, address ) VALUES
( 1, sam, 156, 123 first street), ( 2, smith, 175, 234 second street), ( 3, sean, 191, 345 third street)

我想到了以下方法:

first_part = "INSERT INTO new_table ("
second_part = paste(colnames(my_table), collapse = ", ")

third_part = c(my_table[1,1], my_table[1,2], my_table[1,3], my_table[1,4])
third_part = paste(third_part , collapse = ", ")

fourth_part = c(my_table[2,1], my_table[2,2], my_table[2,3], my_table[2,4])
fourth_part = paste( fourth_part, collapse = ", ")

fifth_part = c(my_table[3,1], my_table[3,2], my_table[3,3], my_table[3,4])
fifth_part  = paste(fifth_part , collapse = ", ")

 final = paste0(first_part,  second_part, "),", " VALUES ", "( ", third_part, " ),", " (" ,fourth_part, " ),", "(", fifth_part, ") ")

生成的输出与期望的输出有些匹配:

> final

"INSERT INTO new_table (id, name, height, address), VALUES ( 1, sam, 156, 123 first street ), (2, smith, 175, 234 second street ),(3, sean, 191, 345 third street) "

最后,我想将这个结果字符串粘贴到 SQL 软件中。

这是解决这个问题的一种非常低效的方法——它非常耗时,而且有很多地方会出错。

  • 谁能告诉我一个“更快”的方法来完成这个?

谢谢!

【问题讨论】:

  • 但是创建的final不是合法的SQL代码,你打算用它来做什么?
  • @r2evans:我想将结果输出粘贴到 SQL 软件中
  • 当然可以,但是 SQL 软件会因您的输入而失败。看我的回答。

标签: sql r string


【解决方案1】:

您的final 不是合法的 SQL,您需要引用您的字符串。

ischr <- sapply(dat, inherits, c("character", "factor"))
dat[ischr] <- lapply(dat[ischr], sQuote, FALSE)
paste(
  "INSERT INTO new_table (",
  paste(colnames(dat), collapse = " , "),
  ") VALUES",
  paste(
    paste0("( ", do.call(mapply, c(list(FUN = paste, sep = " , "), dat)), " )"), 
    collapse = ", "
  )
)
# [1] "INSERT INTO new_table ( id , name , height , address ) VALUES ( 1 , 'sam' , 156 , '123 first street' ), ( 2 , 'smith' , 175 , '234 second street' ), ( 3 , 'sean' , 191 , '345 third street' )"

数据

dat <- structure(list(id = 1:3, name = c("'sam'", "'smith'", "'sean'"), height = c(156L, 175L, 191L), address = c("'123 first street'", "'234 second street'", "'345 third street'")), row.names = c("1", "2", "3"), class = "data.frame")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 2013-02-15
    • 2019-07-03
    • 1970-01-01
    • 2023-03-15
    • 2019-09-15
    • 1970-01-01
    相关资源
    最近更新 更多