我是Cosmos DB中存储过程的新手。但我想要的是在CosmosDB中进行动态输入和输出。
例如,我们有一个数据模型'学生'
{
"FirstName": "Jack",
"LastName": "Louis",
"ZipCode": "12345"
}
我希望能够动态查询这些内容:
SELECT FirstName, LastName FROM Student WHERE FirstName = "Jack"
SELECT FirstName, ZipCode FROM Student WHERE LastName= "Louis"
SELECT ZipCode FROM Student WHERE ZipCode = "12345"
我做了一些研究,发现我仍然需要在存储过程函数中使用SQL Query。对于example:
function(gender) {
var context = getContext();
var response = context.getResponse();
var collection = context.getCollection();
var collectionLink = collection.getSelfLink();
var filterQuery = 'SELECT * FROM c WHERE c.gender = "' + gender + '"';
collection.queryDocuments(collectionLink, filterQuery, {},
function(err, documents) {
response.setBody(response.getBody() + JSON.stringify(documents));
}
);
}
filterQuery变量是SQL Query,我想不出如何在这里做动态输入/输出..
有任何建议或想法吗?谢谢!
答案 0 :(得分:1)
我认为您可以将动态参数组合到SQL查询中以实现动态输入/输出。
请参阅我的示例代码:
function sample(column1,column2,filter,filterValue) {
var collection = getContext().getCollection();
var query = 'SELECT c.' + column1 +',c.'+column2 + ' FROM c where c.' + filter + ' = '+ filterValue;
console.log(query);
var returnArray = [];
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
query,
function (err, feed, options) {
if (err) throw err;
if (!feed || !feed.length) getContext().getResponse().setBody('no docs found');
else {
for(var i = 0;i<feed.length;i++){
var doc = feed[i];
returnArray.push(doc);
}
getContext().getResponse().setBody(returnArray);
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
结果:
如果你的参数数量不确定,我建议你使用query column array
,filter condition array
和filter value array
然后循环解析它们的值,将它们组合成SQL。
希望它对你有所帮助。