Search code examples
rt-sqlrodbctable-variable

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


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?


Solution

  • 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.