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

杀马特。学长 韩版系。学妹 提交于 2019-12-19 09:19:34

问题


I am using the RODBC package which I am applying on a Microsoft SQL Server 2012.

Now I have discovered a phenomenon that puzzles me.

If I run the following query with the RODBC command sqlQuery, then, in R, I will get back an empty data frame with the columns Country, CID, PriceID and WindID.

DECLARE @tbl_IDs TABLE 
(
    Country nvarchar(30),
    CID nvarchar(5),
    PriceID int,
    WindID int
)

SELECT * FROM @tbl_Ids

So far, everything is fine.

However, if I try to write a record to the table variable and execute

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

Then, in R, the result will be an empty character instead of a dataframe with one record. Still the same query works perfectly with SQL Server Management Studio. Also, we have traced the behaviour of the DB Server while the R-Query is executed and it seems the server handles it perfectly. It seems that the RODBC interface has a problem to return the result to the R console.

Does anybody have an idea how this issue can be resolved?


回答1:


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.




回答2:


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");


来源:https://stackoverflow.com/questions/33396013/rodbc-command-sqlquery-has-problems-with-table-variables-in-t-sql

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