c# if condition == null string sqlstr= stringFormat$select ProductionProductNum from ProductProductionRecorderTableMainNameproduction where ProductionDate = StartT
这段代码存在一个作用域问题,即在if语句中定义的变量sqlstr只能在if语句块中访问,而在else语句块中无法访问。
为了解决这个问题,可以在if语句块之前定义一个空字符串变量sqlstr,然后在if语句块和else语句块中分别给它赋值。修改后的代码如下:
string sqlstr = "";
if (condition == null)
{
sqlstr = string.Format($"select {ProductionProductNum} from {ProductProductionRecorderTableMainName}{production} where {ProductionDate} >= '{StartTime}' and {ProductionDate} <= '{EndTime}' ");
}
else
{
sqlstr = string.Format($"select {ProductionProductNum} from {ProductProductionRecorderTableMainName}{production} where {ProductionDate} >= '{StartTime}' and {ProductionDate} <= '{EndTime}' and {ProductionCondition} = '{condition}' ");
}
DataTable dt = SqlConnector.GetDataTable(sqlstr);
此外,还需要注意将查询条件的值用单引号括起来,以便在SQL语句中正确解析。
原文地址: https://www.cveoy.top/t/topic/blcY 著作权归作者所有。请勿转载和采集!