2

I have two tables; viz table1 = PID (primary key) + 20 other columns & 200 records from database1 AND table2 = [Serial no] (primary key) + 10 other columns & 300 records from database2.

I am trying to extract values from table2 where PID = [Serial no].

Note: PID = [SCK34ICV7, NSCK876DL, ......].

I refered "Pass string Variable in R script to use it in SQL statement"

t1 <- sqlquery(db1, "select * from table1")
r1 <- t1$PID
class(r1) = 'factor'
t2 <- sqlquery(db2, "select * from table2 where [Serial no] = '(",r1,")' ",sep ="")

I also tried other functions viz paste0(), fn$ from gsubfn and sprintf() and getting error like - 'c is not a recognized built in function name' ; 'Incorrect syntax'.

Please suggest the best way to do it.

Reg,

Mrutyunjaya

1 Answer 1

3

Your query is off. See here for what the proper format should be.

r1 <- c("PID1","PID2","PID3")

wrong

paste("select * from table2 where [Serial no] = '(",r1,")' ",sep ="")

output:

[1] "select * from table2 where [Serial no] = '(PID1)' " "select * from table2 where [Serial no] = '(PID2)' " "select * from table2 where [Serial no] = '(PID3)' "

correct

paste("select * from table2 where [Serial no] IN (",paste(r1,collapse=", "),") ",sep ="")

Output:

[1] "select * from table2 where [Serial no] IN (PID1, PID2, PID3) "

So the query becomes:

t2 <- sqlquery(db2,paste0("select * from table2 where [Serial no] IN (",paste(r1,collapse=", "),") ",sep =""))

Hope this helps.

Sign up to request clarification or add additional context in comments.

6 Comments

@ Florian, Getting error - 42S22 207 [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid column name 'PID1'. What does this mean.
You should not use my values for r1, I created some dummy data with the line r1 <- c("PID1","PID2","PID3") for my example. You should use your own statement for that.
I used my own vector 'r1'. r1 <- t1$PID
Nope. FYI, str(r1) : Factor w/ 300 levels "SCK34ICV7",..: 334 11465 21762 14917 20282 20927 15958 3514 7430 7207 ...
Well, there has to be the word 'PID1' somewhere in your code? Try CTRL+F and type in PID1.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.