创建动态更新sql查询

时间:2016-11-25 09:55:56

标签: javascript sql

我的问题是,当没有可用于更新它们的值时,我不想更新列。我知道如何在sql中做到这一点,但想做java脚本。

我有一些变量,每个变量只属于需要存储或更新的特定列。

Variable Names    Column Names

context.one       First
context.two       Second
context.three     Third

假设我只在context.one中有价值,而其他人则为空或为空。

我想创建动态更新sql查询。

例如:

Update TableName
Set "column name whose relevant variable is having value" = variable name
Where ID = 100

其他列不应位于set列下,因为它们各自的变量都是空的。

任何建议请!! 感谢

2 个答案:

答案 0 :(得分:1)

您可以创建一个生成查询的函数。只需发送您需要的参数:datacolumn



var context = {
  "one": "Data1",
  "two": "",
  "three": null
}

var columns = {
  "one": "First",
  "two": "Second",
  "three": "Third"
}

//Iterate each keys of context object
Object.keys(context).forEach(function(key) {
  generateUpdateQuery(context[key], columns[key]);
});

function generateUpdateQuery(variableName, column){
  if(variableName === null || variableName === "")
    return;
  var query = "UPDATE table_name SET " + column + "='" + variableName + "' WHERE ID = 100;"
  console.log(query);
}




答案 1 :(得分:0)

修改了Weedoze的函数来回答关于如何创建多列更新查询的问题。

var context = {
  "one": "Data1",
  "two": "Data2",
  "three": null,
  "four": "Data4"
}

var columns = {
  "one": "First",
  "two": "Second",
  "three": "Third",
  "four": "Four"
}

var query = "UPDATE table_name SET ";
Object.keys(context).forEach(function(key) {
  if(!(context[key] === null || context[key] === ""))
    query += columns[key] + "='" + context[key] + "',";  
});

query += " WHERE ID = 100";

//replace last comma from query
var n = query.lastIndexOf(",");
query = query.slice(0, n) + query.slice(n).replace(",", "");

console.log(query);