[英]How can I change vartypes of a SQL table from R using ODBC package?
This works, however I want to change the sepal.width to decimal(28,0).这有效,但是我想将 sepal.width 更改为十进制(28,0)。 Is it possible to do it before writing to SQL, or can I modify the SQL table to change the column type from R?
是否可以在写入 SQL 之前执行此操作,或者我可以修改 SQL 表以从 R 更改列类型?
library(odbc)
library(DBI)
con <- DBI::dbConnect(odbc::odbc(),
Driver = "SQL Server",
Server = "localhost\\SQLEXPRESS",
Database = "testdb",
Port = 1433)
dbWriteTable(con, "test", iris)
I know I can use RODBC, but I am forced to use R Version 3.6, so it is not an option.我知道我可以使用 RODBC,但我被迫使用 R 版本 3.6,所以它不是一个选项。
Look for field.types
when you read ?dbWriteTable
.查找
field.types
当你读?dbWriteTable
。
Without:没有:
# con2 <- dbConnect(...)
library(DBI)
dbWriteTable(con2, "test", iris)
dbGetQuery(con2, "select column_name, data_type, numeric_precision, numeric_precision_radix, numeric_scale from information_schema.columns where table_name='test'")
# column_name data_type numeric_precision numeric_precision_radix numeric_scale
# 1 Sepal.Length float 53 2 NA
# 2 Sepal.Width float 53 2 NA
# 3 Petal.Length float 53 2 NA
# 4 Petal.Width float 53 2 NA
# 5 Species varchar NA NA NA
dbExecute(con2, "drop table test")
# [1] 0
With:和:
dbWriteTable(con2, "test", iris, field.types=c("Sepal.Width"="decimal(28,0)"))
dbGetQuery(con2, "select column_name, data_type, numeric_precision, numeric_precision_radix, numeric_scale from information_schema.columns where table_name='test'")
# column_name data_type numeric_precision numeric_precision_radix numeric_scale
# 1 Sepal.Length float 53 2 NA
# 2 Sepal.Width decimal 28 10 0
# 3 Petal.Length float 53 2 NA
# 4 Petal.Width float 53 2 NA
# 5 Species varchar NA NA NA
dbExecute(con2, "drop table test")
# [1] 0
Tested using docker and the microsoft/mssql-server-linux
image:使用 docker 和
microsoft/mssql-server-linux
镜像进行测试:
$ docker images | grep -E 'REPO|mssql'
REPOSITORY TAG IMAGE ID CREATED SIZE
microsoft/mssql-server-linux latest 314918ddaedf 2 years ago 1.35GB
$ docker run -d -p "11433:1433" --name localss -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=Mysecretpassword1" -e "MSSQL_PID=Developer" --cap-add SYS_PTRACE microsoft/mssql-server-linux
dbGetQuery(con2, "select @@version")[[1]]
# [1] "Microsoft SQL Server 2017 (RTM-CU13) (KB4466404) - 14.0.3048.4 (X64) \n\tNov 30 2018 12:57:58 \n\tCopyright (C) 2017 Microsoft Corporation\n\tDeveloper Edition (64-bit) on Linux (Ubuntu 16.04.5 LTS)"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.