IF语句查询语法错误

时间:2016-04-14 15:06:29

标签: c# mysql

我正在尝试用单个SQL查询替换foreach语句,我想要更改的代码如下所示:

 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();

我希望用以下代码替换上面的代码:

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 null ,它只会显示t1.Default吗?

我尝试过这样的事情:

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

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

2 个答案:

答案 0 :(得分:3)

您可以使用coalesce函数返回列表中的第一个非NULL值,如果没有非NULL值,则使用NULL:

testMockDebugUnitTest

答案 1 :(得分: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