我正在创建一个使用RODBC包从我的MS SQL数据库中提取数据的函数。我目前有功能工作,它将拉取数据,但我似乎无法让原始变量(x)按预期运行。我将T作为虚拟变量来确保函数运行。
但最终我希望能够输入试用版(-CHIP TRAY)或试用版(" -CHIP TRAY"),并且PartNumber = -CHIP TRAY,这样我就可以更改PartNumber使用该功能飞行并获得正确的数据返回 现在它正在运行,但无法按预期更改PartNumber。
trial <- function(x){T=x;
ch <<- odbcConnect("Comp", uid = "user", pwd = "passw");
odbcSetAutoCommit(ch, FALSE);
sqlTables(ch, tableType = "TABLE");
sqlColumns(ch, "Completions");
machines <<- sqlQuery(ch, paste("SELECT WC_or_machine FROM Completions",
"WHERE PartNumber = '-CHIP TRAY'"));
working <<- sqlQuery(ch, paste("SELECT partmadeperhour FROM Completions",
"WHERE PartNumber = '-CHIP TRAY' AND endtime > '2012-12-31 23:59:00'")); T}
因为你可以看到我唯一的结果是vars机器和工作,它们直接取自SQL(我用SQL查询选择的列下的任何内容),最终结果将根据我输入的内容而改变用于指导查询的X值。问题似乎是,一旦R查看sqlQuery命令,它就会停止解释(因此它不会用我给X的任何值替换X)。它只是将我的SqlQuery传递给数据库并返回结果。有办法解决这个问题吗?
这就是我希望它能够工作,但是当我运行该函数时,SqlQuery会忽略我放入的任何内容。
trial <- function(x){T=x;
ch <<- odbcConnect("Comp", uid = "user", pwd = "passw");
odbcSetAutoCommit(ch, FALSE);
sqlTables(ch, tableType = "TABLE");
sqlColumns(ch, "Completions");
machines <<- sqlQuery(ch, paste("SELECT WC_or_machine FROM Completions",
"WHERE PartNumber = 'T'"));
working <<- sqlQuery(ch, paste("SELECT partmadeperhour FROM Completions",
"WHERE PartNumber = 'T' AND endtime > '2012-12-31 23:59:00'")); T}
感谢您的帮助!!
答案 0 :(得分:0)
尝试将粘贴更改为以下内容:
T <- "-CHIP TRAY"
T
#[1] "-CHIP TRAY"
paste0("SELECT partmadeperhour FROM Completions
WHERE PartNumber = '",T,"' AND endtime > '2012-12-31 23:59:00'")
#"SELECT partmadeperhour FROM Completions\n WHERE PartNumber = '-CHIP TRAY' AND endtime > '2012-12-31 23:59:00'"