【问题标题】:String processing for every record in SQL Server and C#SQL Server 和 C# 中每条记录的字符串处理
【发布时间】:2013-12-06 04:52:21
【问题描述】:

我有这张桌子Components:

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

要求是,对于每个ItemDescription,我确定它是Fruit 还是DryFruit,我将值fruit 插入到列Type 中。如果它的类型是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-SQLstring processing stuffs,但是不能满足上面的要求)

【问题讨论】:

  • @bryanmac:不错的收获!但是,我 100% 确定这不会发生。它可以是Refreshing Vegetable drinkRefreshing fruit dring,但不能同时是两者。 (我负责将数据插入表中,这就是我确定的原因)。但是,这是一个很好的收获。

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    下面的查询就可以了。

    UPDATE Components 
    SET [TYPE] = 'FRUIT'
    WHERE ItemDescription LIKE '%Fruit%'
    

    您必须为所有类型重写查询。

    【讨论】:

      【解决方案3】:

      请尝试:

      update Components
      set [Type]=(case when charindex('Fruit', ItemDescription,0)>0 then 'Fruit'
                  else 'Vegetable' end)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-23
        • 1970-01-01
        • 2012-09-29
        • 2019-04-22
        • 1970-01-01
        • 2011-12-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多