使用rstudio中的SQL代码在SQL Server中创建表

发布于 2025-01-22 12:36:11 字数 824 浏览 4 评论 0原文

我的SQL代码如下,但是有更多列,并且在SQL脚本中的此表上也创建了一个非集群索引。

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_NAME = ModelOutput)
BEGIN
    CREATE TABLE ModelOutput
    (
        [OutputID] [bigint] IDENTITY(1,1) NOT NULL,
        [Prediction] [int] NOT NULL,
        [CreateDate] [datetime] DEFAULT CONVERT(DATETIME2(0), getdate()),
    ) ON [PRIMARY]
END;

此代码保存在一个名为createTable.sql的文件中,我想使用rstudio运行。

当前,我的R代码看起来像:

#Read SQL file
sqlcode = read_file(file = "CreateTable.sql")

#Run SQL code
DBI::dbSendQuery(conn = con, statement = sqlcode)

但是,当我试图弄清为什么它似乎没有运行时,我发现dbsendquery()仅与Select语句一起使用(

我环顾四周,找不到任何方法来运行Rstudio的Create Table SQL语句。我有什么选择,还是我需要完全重新考虑我的过程以使用dbCreateTable()

I have SQL code like below, but with more columns and I also create a nonclustered index on this table within the sql script.

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_NAME = ModelOutput)
BEGIN
    CREATE TABLE ModelOutput
    (
        [OutputID] [bigint] IDENTITY(1,1) NOT NULL,
        [Prediction] [int] NOT NULL,
        [CreateDate] [datetime] DEFAULT CONVERT(DATETIME2(0), getdate()),
    ) ON [PRIMARY]
END;

This code is saved in a file called CreateTable.sql which I want to run using RStudio.

Currently, my R code looks like:

#Read SQL file
sqlcode = read_file(file = "CreateTable.sql")

#Run SQL code
DBI::dbSendQuery(conn = con, statement = sqlcode)

However, when I tried to figure out why it didn't seem to be running, I found that dbSendQuery() only works with select statements (https://cran.r-project.org/web/packages/DBI/vignettes/DBI-advanced.html). So then I found dbCreateTable() but that only works if I have created the table using R. I don't want to do that since I can't set the same column defaults or create an index--as far as I know.

I have looked around and cannot find any way to run a create table SQL statement from RStudio. Are there any options for me or do I need to rethink my process entirely to just use dbCreateTable()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怕倦 2025-01-29 12:36:11

我尝试了许多选项,并找到了从rstudio connect运行任何SQL代码的最可靠方法,对我来说,Rstudio Server Pro是将其转换为过程。然后运行dbi :: dbsendquery(con,“在\ nexec yourprocedure上设置nocount”)

I tried many options and found the most reliable way to run any SQL code from RStudio Connect and RStudio Server Pro for me was to turn it into a procedure. Then run DBI::dbSendQuery(con, "SET NOCOUNT ON\nEXEC YourProcedure")

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文