6

I've got a very basic SQL query that I'd like to be able to view in R.

The trouble is, I need to be able to reference a #table:

    select
    RAND(1) as random
    into #test

    select * from #test

Is this possible, or will I need to create permanent tables, or find some other work around?

I currently do this via a RODBC script which allows me to choose which SQL file to run:

    require(RODBC)
    sql.filename <- choose.files('T:\\*.*')
    sqlconn <- odbcDriverConnect("driver={SQL Server};Server=SERVER_NAME;Trusted_Connection=True;")
    file.content <- readLines(sql.filename)
    output <- sqlQuery(sqlconn, paste(file.content[file.content!='--'],collapse=' '))
    closeAllConnections()

Do you have any advice on how I can utilise #tables in my SQL scrips in R?

Thanks in advance!

2 Answers2

2

When you use temp tables SQL outputs a message with the number of rows in the table. R doesn't know what to do with this message. If you begin your SQL query with SET NOCOUNT ON SQL will not output the count message.

Cody
  • 21
  • 2
0

I use #tables by separating my query into two parts, it returns character(0) if I do like:

sqlQuery(test_conn, paste("
drop table #test;
select
       RAND(1) as random
     into #test

select * from #test
"))

So instead I would use:

sqlQuery(test_conn, paste("
drop table #test;
select
       RAND(1) as random
    into #test
"))

sqlQuery(test_conn,"select * from #test")

It seems to work fine if you send one Query to make the #table, and a second to retrieve the contents. I also added in drop table #test; to my query, this makes sure there is not already a #test. If you try to write to a #table name that is already there you will get an error

DrewH
  • 1,657
  • 3
  • 14
  • 10