两个不同列的SQL或条件

时间:2016-08-27 08:07:12

标签: sql sql-server-2008 tsql

我有两个字段(@ EmployeeId,@ SSOId),其中一个值可以来或两者都可以来,但是当我应用OR条件时它不会给我正确的输出。我做错了什么?

ALTER PROCEDURE [dbo].[usp_User_GetDetails] ( 
@UserId INT = NULL 
,@ADSId NVARCHAR(32) = NULL 
,@EmployeeId NVARCHAR(32) = NULL 
,@SSOId NVARCHAR(32) = NULL 
,@UserName NVARCHAR(100) = NULL 
) 
AS 

*/ 
SET NOCOUNT ON; 
BEGIN 
SELECT [USER_ID] AS UserId 
,[FIRST_NM] AS FirstName 
,[LST_NM] AS LastName 
,[FULL_NM] AS FullName 
,[ADS_USER_ID] AS ADSId 
,[SEG_ID] AS SegmentId 
,[PHONE_NO] AS PhoneNo 
,[FAX_NO] AS FaxNo 
,[EMP_ID] AS EmployeeId 
,[EMAIL_AD_TX] AS Email 
,[SSO_ID] AS SSOId 
,[SFDC_IN] AS IsSFDC 
,[USER_SFDC_ID] AS UserSFDCId 
,[MGR_SFDC_ID] AS ManagerSFDCId 
,[ACT_IN] AS IsActive 
,[SYS_USER_IN] AS IsSystemUser 
,[PORFOLIO_OWN_IN] AS CanHavePortfolio 
,[MGR_ID] AS ManagerId 
,[LST_LOG_IN_TS] AS LastLoginDate 
,[EMP_BAND_TX] AS Band 
,[CREAT_TS] AS CreatedDate 
,[CREAT_BY_USER_ID] AS CreatedBy 
,[LST_UPDT_TS] AS UpdatedDate 
,[LST_UPDT_BY_USER_ID] AS UpdatedBy 
FROM [dbo].[USER] WITH (NOLOCK) 
WHERE ([EMP_ID] = ISNULL(@EmployeeId, [EMP_ID])OR [SSO_ID] = ISNULL(@SSOId, [SSO_ID]) 
AND [ADS_USER_ID] = ISNULL(@ADSId, [ADS_USER_ID]) 
AND [USER_ID] = ISNULL(@UserId, [USER_ID])
AND [FULL_NM] LIKE CASE 
WHEN @UserName IS NOT NULL 
THEN '%' + @UserName + '%' 
ELSE [FULL_NM] 
END 
END 

4 个答案:

答案 0 :(得分:2)

我认为括号没有正确平衡。无论如何,我会在没有ISNULL()

的情况下写这个
WHERE ((@EmployeeId IS NULL OR EMP_ID = @EmployeeId) OR
       (@SSOId IS NULL OR SSO_ID = @SSOId)
      ) AND
      (@ADSId IS NULL OR ADS_USER_ID = @ADSId) AND 
      (@UserId IS NULL OR USER_ID = @UserId) AND 
      (@UserName IS NULL OR FULL_NM LIKE '%' + @UserName + '%') 

我猜测OR是前两个条件。这是parens在问题中的查询中似乎没有对齐的地方。

我更喜欢这种结构有两个原因。首先,它处理列值中的NULL以及参数值。第二 - 因为它更通用 - 它是我用来处理可选参数的标准两种方法之一(另一种是使用可以使用索引的动态SQL)。

答案 1 :(得分:0)

查询似乎没问题。你从C#代码或空文本传递DBNull

答案 2 :(得分:0)

WHERE (@EmployeeId IS NULL OR (EMP_ID = @EmployeeId)) 
AND   (@SSOId IS NULL OR (SSO_ID = @SSOId))
AND [ADS_USER_ID] = ISNULL(@ADSId, [ADS_USER_ID]) 
AND [USER_ID] = ISNULL(@UserId, [USER_ID])  
AND [FULL_NM] LIKE CASE 
WHEN @UserName IS NOT NULL 
THEN '%' + @UserName + '%' 
ELSE [FULL_NM]

答案 3 :(得分:0)

使用此脚本

WHERE EMP_ID = ISNULL时的情况(@ EmployeeId,0)> 0那么@EmployeeId ELSE EMP_ID END AND SSO_ID = CASN when ISNULL(@ SSOId,0)> 0那么@SSOId ELSE SSO_ID END