【发布时间】: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 软件会因您的输入而失败。看我的回答。