c# - SQL Server 和 C# 中每条记录的字符串处理

标签 c# sql .net sql-server sql-server-2008

我有这张表组件:

ItemNo  ItemDescription                Type
  1     Apple Fruit 20Kg               null
  2     Carrot Veg  1Kg                null
  3     Fig DryFruit 100g              null

要求是,对于每个 ItemDescription,我确定它是 Fruit 还是 DryFruit,我插入值 fruitType 列。如果它的类型是 Veg,那么我将值 Vegetable 放入 Type 列。

结果表如下所示:

ItemNo  ItemDescription                Type
  1     Apple Fruit 20Kg               Fruit
  2     Carrot Veg  1Kg                Vegetable
  3     Fig DryFruit 100g              Fruit

我如何实现这一点?

使用 C# 代码:

var itemDescription = GetAllItemDescription() //Executes  'select ItemDescription from Components;' SQL query
itemDescription.ForEach(item=>{
     if(item.Contains("Fruit") || item.Contains("DryFruit"))
     {
        EnterFruitInTypeColumn() //contains sql query which does the corresponding stuff.
     }
    ........
}

问题是:

我应该如何只使用 SQL 语句来做同样的事情?

(我也知道有T-SQL string processing stuffs ,但无法满足上述要求)

最佳答案

与其他答案一样,这应该可以帮助您:

UPDATE Components
SET [Type] = CASE WHEN CHARINDEX('DryFruit', ItemDescription) > 0 THEN 'Fruit'
                  WHEN CHARINDEX('Veg', ItemDescription) > 0 THEN 'Vegetable'
                  WHEN CHARINDEX('Fruit', ItemDescription) > 0 THEN 'Fruit'
                  ELSE null
             END

关于c# - SQL Server 和 C# 中每条记录的字符串处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20416242/

相关文章:

mysql - SQL触发器不工作

c# - 如何自定义 MSI 安装程序中的错误屏幕?

c# - 基于行选择的Datagridview SelectionChanged事件

.net - 如何在 C# 中将屏幕截图与剪贴板上的副本分开

c# - 在 LineSeries WinForms 图表中显示工具提示?

php - 来自 SQL 的值数组,显示哪些存在,哪些不存在

java - 如何为 SQL 插入转义单引号...当要插入的字符串在用户生成的变量中时

c# - Visual Studio 项目代码分析器路径已更改

c# - 我如何模拟 UserManager.GetRoles()

c# - 如何让 ActionFilters 和 OutputCaching 一起工作?