SQL Server 2012を使用しています。特定の条件でWHERE句を設定しようとしています。 PAE.CaseStatusIdには値1,2,4,8,16が含まれています。考えられるのはBitwise &を使用してWHEREの条件を選択することです。たとえば、@ CaseStatusSum = 3の場合は、CaseStatusId IN(1,2)を選択します。 ifCaseStatusSum = 4の場合は、CaseStatusId = 4などを選択します.IFFまたはCASEで条件を設定する際に問題があります。とにかくこの問題を解決するにはどうかと思います。すべての入力をいただければ幸いです。ありがとうございました。SQL Server 2012 WHERE CONDITION IFF Case..WHEN
CREATE PROCEDURE [dbo].[getPagingPatientLiteByNameTest]
(
@CaseStatusSum INT,
@FilterCriteria NVARCHAR(50),
@PageNo INT = 1,
@PageSize INT = 10,
@SortColumn NVARCHAR(40) = 'OperationDate',
@SortOrder NVARCHAR(4) = 'DESC'
)
AS
BEGIN
DECLARE
@lFilter NVARCHAR(50),
@lSortCol NVARCHAR(40),
@lFirstRec INT,
@lLastRec INT,
@lTotalRows INT,
SET NOCOUNT OFF
/* Setting local variable */
SET @lFilter = LTRIM(RTRIM(@FilterCriteria))
SET @lSortCol = LTRIM(RTRIM(@SortColumn))
SET @lFirstRec = (@PageNo - 1) * @PageSize + 1
SET @lLastRec = @PageNo * @PageSize
SET @lTotalRows = @lLastRec - @lFirstRec + 1
; WITH CTE_Results
AS (
SELECT ROW_NUMBER() OVER (ORDER BY
CASE WHEN (@SortColumn = 'OperationDate' AND @lSortCol = 'ASC')
THEN OpDate
END ASC,
CASE WHEN (@SortColumn = 'OperationDate' AND @lSortCol = 'DESC')
THEN OpDate
END DESC,
CASE WHEN (@SortColumn = 'HN' AND @lSortCol = 'ASC')
THEN HN
END ASC,
CASE WHEN (@SortColumn = 'HN' AND @lSortCol = 'DESC')
THEN HN
END DESC,
CASE WHEN (@SortColumn = '')
THEN OpDate
END DESC
) AS ROWNUM,
Count(*) over() AS TotalCount,
Id,
RecOut,
CaseStatusId,
LastName,
OpDate
FROM PAE
WHERE
(CaseStatusId = (
CASE @CaseStatusSum
WHEN 1 THEN 1
WHEN 2 THEN 2
WHEN 4 THEN 4
WHEN 8 THEN 8
WHEN 16 THEN 16
END)
/* MS SQL Server 2012
In the following commented section, neither IIF nor IF..ELSE work.
My goal is IF @CaseStatusSum = 3 THEN select CaseStatusSum IN (1, 2) and
IF @CaseStatusSum = 8 THEN select CaseStatusSum IN (8)/CaseStatusSum = 8
-- here is the problem, I am unable to get 1, 2 out of IIF to the IN condition
OR CaseStatusId IN (IIF(@CaseStatusSum = 3, (1 2), 0))
-- here is the problem: IF is not allow in this structure
OR IF (@CaseStatusSum = 3)
BEGIN
CaseStatusId IN (1, 2)
END
ELSE
BEGIN
CaseStatusId = 4
END
END IF
*/
OR CaseStatusId = (
CASE @CaseStatusSum
WHEN 1 THEN 4
WHEN 2 THEN 2
WHEN 4 THEN 4
WHEN 8 THEN 8
WHEN 16 THEN 16
END)
)
AND RecOut > getDate()
AND (@lFilter IS NULL OR (LastName LIKE @lFilter))
)
SELECT
TotalCount,
Id,
RecOut,
CaseStatusId,
LastName,
OpDate
FROM CTE_Results
WHERE
ROWNUM BETWEEN @lFirstRec AND @lLastRec
ORDER BY ROWNUM ASC
END