You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中DataTable使用带CASE的Select语句报错求助

Fixing the "Missing operand after 'WHEN' operator" Error in DataTable Filtering

Hey there! Let's break down why your C# DataTable filter is throwing that error, and how to fix it.

The Root Cause

The DataTable.Select() method uses DataColumn.Expression syntax, which doesn't support the SQL-style CASE WHEN statement you're trying to use. That's exactly why you're seeing the "Missing operand after 'WHEN' operator" error—this syntax just isn't recognized here.

The Solution

Your logic is trying to:

  • Return all rows when MakerBy.Trim() equals "A" (since MAKER_BY = MAKER_BY is always true)
  • Return only rows where MAKER_BY matches the trimmed MakerBy value otherwise

We can rewrite this logic without CASE WHEN using a simple conditional check in C# before building the filter expression:

DataTable dt = (DataTable)ViewState["FilteredData"];
string trimmedMakerBy = MakerBy.Trim();

// Handle the two cases directly in C#
string filterExpression;
if (trimmedMakerBy == "A")
{
    // Return all rows (since MAKER_BY always equals itself)
    filterExpression = "MAKER_BY = MAKER_BY";
}
else
{
    // Escape single quotes to avoid syntax errors if the value contains them
    string safeMakerBy = trimmedMakerBy.Replace("'", "''");
    filterExpression = $"MAKER_BY = '{safeMakerBy}'";
}

dt = dt.Select(filterExpression).CopyToDataTable();

Bonus: Avoiding Syntax Errors

Notice the Replace("'", "''") part—this is important because if your MakerBy value contains a single quote, it will break the filter expression. Escaping single quotes by doubling them ensures the expression stays valid.

Alternative with IIF (If You Prefer Inline Logic)

If you want to use an inline conditional in the expression (similar to CASE but supported by DataColumn syntax), you can use the IIF function. Here's how that would look:

string trimmedMakerBy = MakerBy.Trim();
string safeMakerBy = trimmedMakerBy.Replace("'", "''");
string filterExpression = $"IIF('{safeMakerBy}' = 'A', MAKER_BY = MAKER_BY, MAKER_BY = '{safeMakerBy}')";

dt = dt.Select(filterExpression).CopyToDataTable();

Either approach will fix your error and implement your desired filtering logic.

内容的提问来源于stack exchange,提问作者Abhishek Jain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:34:36