2016-04-14 130 views
1

我试图取代foreach语句一个SQL查询,我的代码,我想改变这样的容貌:IF语句的查询语法错误

this.Settings = new List<Setting>() 
     { 
      // Write all the settings from the VB 
      new Setting() { Name = "NOOFORDERS", Value = null }, 
      new Setting() { Name = "ORDNVGREQ", Value = null }, 
      new Setting() { Name = "IncWendsDel", Value = null }, 
      new Setting() { Name = "AUTOEMAIL_INVOICE", Value = null }, 
      new Setting() { Name = "REQEMAIL_INVOICE", Value = null }, 
      new Setting() { Name = "REQEMAIL_SALES", Value = null }, 
      new Setting() { Name = "REQEMAIL_PICKSLIP", Value = null }, 
      new Setting() { Name = "REQEMAIL_DESPATCH", Value = null }, 
      new Setting() { Name = "CARRPARTSHIP", Value = null }, 
      new Setting() { Name = "DELNOTEREQ", Value = null }, 
      new Setting() { Name = "REQ_CARRPARTSHIP", Value = null }, 
      new Setting() { Name = "BUDGETREQ", Value = null }, 
      new Setting() { Name = "PriceList", Value = null }, 
      new Setting() { Name = "EmployeeRenew", Value = null }, 
      new Setting() { Name = "Warehouse", Value = null }, 
      new Setting() { Name = "EmployeeDetails", Value = null }, 
     }; 
var value = this.db.tblbus_setvalues.Where(x => x.SettingID == setting.Name && x.BusinessCode == this.Business.BusinessCode).FirstOrDefault().Value; 
switch (value.GetType()) 
{ 
    case typeof(bool): 
     (value) ? setting.Value = "true" : setting.Value = "false"; 
     break; 
    default: 
     setting.Value = value.ToString(); 
     break; 
    } 
    if (!string.IsNullOrEmpty(setting.Value)) setting.Value = this.db.tblbus_settings.Where(x => x.SettingID == setting.Name).FirstOrDefault().Default.ToString(); 

我的SQL,我想,以取代上面的代码看起来是这样的:

SELECT t1.SettingID, t2.Value, t1.Default 
FROM `tblbus_settings` t1 
LEFT JOIN `tblbus_setvalues` t2 
ON t1.SettingID = t2.SettingID 
WHERE `BusinessCode` = "XXX" // Dependency 
AND t1.`BusType` = "CUS" 

谁能帮我写一个IF语句到这个SQL查询,这将只显示t2.Value如果t1.Default

我试过的东西:

IF(t2.value == NULL) { t1.Default } 
ELSE { t2.Value } 

但他们都给予我的SQL语法错误。

回答

3

看到这个你可以使用coalesce函数列表返回第一个非NULL值,或NULL如果没有非NULL值:

SELECT t1.SettingID, COALESCE(t2.Value, t1.Default) FROM ... 
+0

这返回了141行,应该有150行:/奇怪 - 调查时间,但感谢来源!我会在可以时标记它 – KDOT

+0

这是比我提交的更好的答案,请与此:) –

2

像这样的事情?

SELECT t1.SettingID, t2.Value, t1.Default, 
CASE t1.Default IS NOT NULL 
    THEN t1.Default 
    ELSE t2.Value 
FROM `tblbus_settings` t1 
LEFT JOIN `tblbus_setvalues` t2 
ON t1.SettingID = t2.SettingID 
WHERE `BusinessCode` = "XXX" // Dependency 
AND t1.`BusType` = "CUS" 

为meore https://msdn.microsoft.com/en-gb/library/ms181765.aspx