【问题标题】:SQL Change a parameters value of a list of strings /varchar to a list of integersSQL将字符串列表/varchar的参数值更改为整数列表
【发布时间】:2018-12-20 14:09:44
【问题描述】:

如何更改由以下 case 语句生成的参数值:

Set @CostType=Case When @ShowLabor ='Y'and @ShowEquipment ='Y' then ('1,3,5,7,8')
                when @ShowLabor ='Y'and @ShowEquipment ='N' then ('3,5')
                when @ShowLabor ='N'and @ShowEquipment ='Y' then ('1,7,8')
                else ('1,3,5,7,8') end

到整数列表 [EX:(1,3,5,7,8)] 以成为此 IN 语句的一部分:

Where JCCD.CostType in (@CostType) 

我也尝试将其作为临时表中的一列,如下所示,让我知道这是否更容易转换:

Declare @TempTable table (CostType int)
Set NOCOUNT ON;
Insert into @TempTable values 
(Case When @ShowLabor ='Y'and @ShowEquipment ='Y' then ('1,3,5,7,8')
      when @ShowLabor ='Y'and @ShowEquipment ='N' then ('3,5')
      when @ShowLabor ='N'and @ShowEquipment ='Y' then ('1,7,8')
      else   ('1,3,5,7,8') end )

【问题讨论】:

    标签: sql string casting integer


    【解决方案1】:

    我建议将您的 TempTable 标准化,如下所示:

    ShowLabor | ShowEquipment | CostType
    1         | 1             | 1
    1         | 1             | 3
    1         | 1             | 5
    1         | 1             | 7
    1         | 1             | 8
    1         | 0             | 3
    1         | 0             | 5
    0         | 1             | 1
    0         | 1             | 7
    0         | 1             | 8
    

    通过这个重构,您可以编写一个适当的查询:

    SELECT *
    FROM JCCD
    WHERE CostType IN (SELECT CostType FROM TempTable
                       WHERE ShowLabor = 1 AND ShowEquipment = 1);
    

    一般而言,将 CSV 数据存储到数据库中的单个列/行中并不是一个好的做法。如上所示,将每个成本类型值放在单独的行上会更好。

    【讨论】:

    • 非常感谢,效果很好,在我使用它之前我遇到了困难。
    猜你喜欢
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    相关资源
    最近更新 更多