不确定这是否可能,在字符串sql变量中使用if语句
本文关键字:变量 语句 if sql 字符串 是否 不确定 | 更新日期: 2023-09-27 18:21:44
我将一个长sql查询字符串保存到一个变量中。
1 sSQL ="select a bunch of stuff from multiple tabled" +
2 "where conditions are met" +
3 "and other conditions are met" +
4 "order by these columns";
我现在需要做的是在3和4之间添加一行if语句。或者,我需要找到一些其他方法,不需要我放入两个巨大的sql代码块,除了一行代码外,这些代码块大多是多余的。
所需代码:
if (proSeries)
{
"unique sql code to add only if proSeries is true" +
}
它不喜欢字符串中的块。我能想到的唯一其他方法就是将整个sql字符串复制到两个单独的变量中,并将它们放入if/else中。
变量声明中不能有条件逻辑。但是,您可以利用StringBuilder
:
StringBuilder sqlText = new StringBuilder();
sqlText.AppendLine("select a bunch of stuff from multiple tabled");
...
if (proSeries)
{
sqlText.AppendLine("unique sql code to add only if proSeries is true");
}
sqlText.AppendLine("order by these columns");
string finalText = sqlText.ToString();
如果你经常运行它,你可以很容易地将其封装在函数调用中。
当涉及到具有多个条件时,我有时会执行以下操作,我认为这些操作非常可读:
sSQL = "select a bunch of stuff from multiple tables " +
"where conditions are met " +
"#AND_PROSERIES_CRITERIA# " +
"and other conditions are met " +
"order by these columns ";
// Build all criteria strings
String sProSeriesCriteria = (proSeries) ? "and ....." : "";
// Insert all criteria
sSQL = sSQL.Replace("#AND_PROSERIES_CRITERIA#", sProSeriesCriteria);
好吧,如果有更多的标准,效果会更好,例如选择所有订单
- 来自所有供应商或仅限于某些供应商
- 适用于所有产品或仅适用于某些产品
- 存在或不存在的返回在另一个表中
你明白了。有了许多这样的可选条件,您仍然可以编写一个可读的查询,然后计算出各个部分。