문제

데이터베이스에 저장된 정수가 있습니다 (Sqlagent 주파수 간격)이 정수는 실제로 일정이 선택된 요일의 합계는 가능한 값을 실행하는 것이 이러한 값의 조합입니다.

  • 일요일 = 1
  • 월요일 = 2
  • 화요일 = 4
  • 수요일 = 8
  • 목요일 = 16
  • 금요일 = 32
  • 토요일 = 64

Ex 65는 일정이 토요일과 일요일에 실행되어야 함을 의미합니다.

내 문제는이 값을 65 년에 주어지면 "토요일"과 "일요일"으로이 값을 표현해야한다는 것입니다.

가능한 모든 조합이있는 거대한 사례 진술 이외의 다른 사람 이이 작업을 수행 할 수있는 방법을 생각할 수 있습니까?

감사

도움이 되었습니까?

해결책

T-SQL에서 비트 현행 연산자를 사용할 수 있습니다. 방법은 다음과 같습니다.

SELECT
  ( CASE WHEN daybits & 1 = 1 THEN 'Sunday ' ELSE '' END ) +
  ( CASE WHEN daybits & 2 = 2 THEN 'Monday ' ELSE '' END ) +
  ( CASE WHEN daybits & 4 = 4 THEN 'Tuesday ' ELSE '' END ) +
  ...
  ( CASE WHEN daybits & 64 = 64 THEN 'Saturday ' ELSE '' END ) +

예를 들어 "일요일 토요일"을 생산할 것입니다.

다른 팁

I would start by putting it on an user defined function. Also, you can use an and that operates at the bit level to check for it - I think it is &, will update.

Update 1: It was &, Jason already put up an example. I still recommend to use an user defined function for it :).

Edit: This is C# code to do the bit operations. I posted it before reading the question in detail, but I will leave it here as an alternative. Is the database really the best place to do this...?

You can use an array:

// input: int value
string[] weekdays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Saturday" };
int flag = 1
List<string> days = new List<string>();
foreach (string day in days) {
   if ((value && flag) != 0) {
      days.Add(day);
   }
   flag <<= 1;
}

The result is a list of strings, if you want to merge them you can for example do:

string selected = String.Join(", ", days.ToArray());
DECLARE @in INTEGER;
SET @in = 63;
WITH series(n) AS
    (
    SELECT  0
    UNION ALL
    SELECT  n + 1
    FROM    series
    WHERE   n < 6
    )
SELECT  CASE WHEN ROW_NUMBER() OVER (ORDER BY n) > 1 THEN ', ' ELSE '' END + DATENAME(weekday, DATEADD(day, n, '1980-09-03')) 
FROM    series
WHERE   (POWER(2, n) & @in) > 0
ORDER BY n
FOR XML PATH ('')
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top