我想知道它是否可能,而且肯定是必须的。我想基本上根据用户输入有条件地创建一个动态SQL语句(对于这个例子,我们将使用3个文本框输入):
var firstname = document.getElementById('firstname').value
var middle = document.getElementById('middle').value
var lastname = document.getElementById('lastname').value
var SQL
(如果填写了所有3个字段......)
SQL = "SELECT * FROM TABLE WHERE [Firstname] = '" + firstname + "' AND [Middle] = '" + middle + "' AND [Lastname] = '" + lastname + "'"
(如果填写了3个字段中的2个......)
SQL = "SELECT * FROM TABLE WHERE [Firstname] = '" + firstname + "' AND [Lastname] = '" + lastname + "'"
有更好的方法吗?更短的东西?或者我是否必须评估每个字段中的文本然后定义SQL?
只是想知道,但问问题永远不会伤害。
杰
答案 0 :(得分:0)
这样的事情应该有用......
SQL = "SELECT * FROM TABLE WHERE
1 =
(
case
when LEN('" + firstname + "') > 0 and LEN('" + lastname + "') > 0 and LEN('" + middle + "') > 0 then ([Firstname] = '" + firstname + "' AND [Lastname] = '" + lastname + "' AND [Middle] = '" + middle + "')
when LEN('" + firstname + "') = 0 and LEN('" + lastname + "') > 0 and LEN('" + middle + "') > 0 then ([Lastname] = '" + lastname + "' AND [Middle] = '" + middle + "')
...
end
)
或更好:
SQL = "SELECT * FROM TABLE WHERE
(
(LEN('" + firstname + "') > 0 AND [FirstName] = '" + firstname + "')
OR
LEN('" + firstname + "') = 0
)
AND (same for secondName)
AND (same for middle)"
答案 1 :(得分:0)
如果能够将参数中的值传递给查询,那么
SQL = " SELECT *
FROM TABLE
WHERE (@firstName is null OR [FirstName] = @firstName)
AND (@middle is null OR [Middle] = @middle)
AND (@lastName is null OR [Lastname] = @lastName"
这也会阻止查询缓存被垃圾邮件,因为您只会在缓存中存储1个查询计划。
答案 2 :(得分:0)