我有这个:
int id = 10;
long partnerId = 20;
long? groupId = null;
DateTime startDate = Datetime.Now.AddDays(-5);
DateTime endDate = Datetime.Now;
bool isTesting = true;
bool isActive = false;
query = @"SELECT Vita as VitalLevel,count(distinct ccrid) as Answers, Vitald as VitalType
FROM CORE.vRecipientsc rd
INNER JOIN Recipiendy rs ON rs.CRRID = rd.RID
INNER JOIN RecipientStungs rsvr ON rsvr.StudyId = rs.Id
WHERE SBURID = {0}
AND ({5} IS null OR {5}=SbuGroupRID)
AND rs.DTUTC_Created >= '{1}'
AND rs.DTUTC_Created <= '{2}'
AND rsvr.VitalTypeId = 8
AND rsvr.VitalValue <> ''
AND (rd.isTesting = {3} or rd.isTesting = 0)
AND rd.IsActive= {4}
GROUP BY rsvr.VitalValue, rsvr.VitalLevel, rsvr.VitalTypeId";
String.Format(query, new object[] {
partnerId, startDate, endDate, Convert.ToInt32(isTesting), Convert.ToInt32(isActive), groupId
});
然后,我与数据库和执行多个查询有一个连接,但是当我执行查询时,在string.format中替换了空格中的null值,我希望将线直接替换为groupID变量设置为null。我可以使用C#?
您可以使用string.format方法(String,Object [](和??对于无效的值。
String.Format(query, partnerId, startDate, endDate, Convert.ToInt32(isTesting), Convert.ToInt32(isActive), groupId ?? "null");
,或者您可以使用相同的方法和三元运算符
String.Format(query, new object[] { partnerId, startDate, endDate, Convert.ToInt32(isTesting), Convert.ToInt32(isActive), groupId != null ? groupId.ToString() : "null" });
您可以将行本身用作最后一个参数:
用{5}
替换AND ({5} IS null OR {5}=SbuGroupRID)
,并将最后一个参数的值设置为groupId.HasValue ? string.Format("AND ({0} IS null OR {0}=SbuGroupRID)", groupId) : string.Empty
您可以在查询字符串之前将其移至另一个变量中,然后将该变量用作最后一个参数。