Sql 将数字字符串转换为 int

Sql convert string of numbers to int

我想 select 工作日或整周,具体取决于参数。

我正在考虑使用 case 语句来执行以下操作,但我不知道如何将数字字符串转换为可以作为整数传递的值。

我可能做错了,但我们将不胜感激。

这是我设置参数值的地方:

set @days = (select case when FullWeek = 1 then cast('1,2,3,4,5,6,7' as Numeric(38,0))
                        when fullweek = 0 then cast('2, 3,4,5,6' as Numeric(38,0)) end 
            from Reports)

这就是我想要调用它的方式,它是 where 语句的一部分:

where datepart(dw,date) in (@days)

这甚至不是 sql 的问题,这是一个概念性的问题。您不能将此类值转换为数字。您期望每种情况下的数值是多少?

当您尝试将分隔字符串转换为数组时,您正在犯一个非常常见的初学者错误。在这种情况下你应该做的是:

where datepart(dw,date) in 
    case 
        when FullWeek = 1 then
            (1,2,3,4,5,6,7)
        else -- if fullweek is a bit. otherwise use when fullweek = 0 then
            (1,2,3,4,5,6,7)
        end

为什么不简化它并这样做:

Where (Fullweek = 1) -- Will get all days of week
   or 
      (Fullweek = 0 and datepart(dw,date) in (2,3,4,5,6))

我不想在查询中对值进行硬编码。我宁愿这样做:

创建一个 table 来对天进行分类:

  Day    isWeekday   biWeeklyReportDays
  1        0              0
  2        1              1
  3        1              0
  4        1              0
  5        1              1
  6        1              0
  7        0              0

我的查询是这样的。

IF FullWeek = 0
BEGIN
SELECT @days = days FROM theTable where isWeekDay = 1
END
ELSE
BEGIN
SELECT @days = days FROM theTable
END

----
where datepart(dw,date) in @days