RODBC command 'sqlQuery' has problems with table variables in t-SQL

我的梦境 提交于 2019-12-01 06:28:41

Try toggling NOCOUNT as below:

old_qry <- "
DECLARE @tbl_IDs TABLE 
(
    Country nvarchar(30),
    CID nvarchar(5),
    PriceID int,
    WindID int
)

INSERT INTO @tbl_IDs
VALUES 
    ('Germany', 'DE', 112000001, 256000002);

SELECT * FROM @tbl_Ids
"
##
new_qry <- "
SET NOCOUNT ON;
DECLARE @tbl_IDs TABLE 
(
    Country nvarchar(30),
    CID nvarchar(5),
    PriceID int,
    WindID int
);

INSERT INTO @tbl_IDs
VALUES 
    ('Germany', 'DE', 112000001, 256000002);
SET NOCOUNT OFF;
SELECT * FROM @tbl_Ids
"

R> sqlQuery(tcon, gsub("\\n", " ", old_qry))
#character(0)
R> sqlQuery(tcon, gsub("\\n", " ", new_qry))
#  Country CID   PriceID    WindID
#1 Germany  DE 112000001 256000002

Basically you want to SET NOCOUNT ON at the beginning of your code, and SET NOCOUNT OFF just before the final SELECT statement.

Since database server handles query correctly, save the multiple line action TSQL query as a SQL Server Stored Procedure and have R call it retrieving the resultset.

Do note you can even pass parameters in the EXEC sp line from R to MSSQL. Also as mentioned, include the SET NOCOUNT ON declaration in the query to avoid undesired result character(0):

library("RODBC");
conn <- odbcConnect("DSN Name",uid="***",pwd="***");   # WITH DSN
#conn <-odbcDriverConnect('driver={SQL Server};server=servername;database=databasename;
                        #trusted_connection=yes;UID=username;  PWD=password')  # WITH DRIVER

df<-sqlQuery(conn, "EXEC dbo.StoredProcName");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!