带有布尔问题的SQL Server查询

时间:2012-10-29 22:02:18

标签: sql sql-server-2008 tsql sql-server-2005

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

alter PROCEDURE [dbo].[TCCPAUsersAndNamesByJobPosition] @EmpOrfreeLance bit

AS
BEGIN
    SET NOCOUNT ON;

    SELECT distinct t1.UserId , tblCustomers.name 
    FROM tblTime t1
    inner join tblCustomers on t1.UserId=tblCustomers.custID
    where (t1.userid in (select distinct custID from tblCustomers where sectionCat Like '%,35%') )
    AND (t1.UserId in (select distinct custID from tblCustomers where IsEmployee = @EmpOrfreeLance))

end

也尝试使用IsEmployee = CONVERT(bit,@EmpOrfreeLance)

SET @EmpOrfreeLance= CASE @EmpOrfreeLance WHEN 1 THEN 0 ELSE 0 END

同样,无论什么

,它都会以相同的结果返回相同的列表

不应该很简单???

IsEmployee col-datatype为(bit,null)

我的开发SQL服务器是2008 ..在线服务器是2005应该是一件事......

3 个答案:

答案 0 :(得分:2)

比较空值将始终返回false。您已声明IsEmployee可能为null,这可能是您的情况。

1 == NULL => False
0 == NULL => False
NULL == NULL => False

尝试使用类似的东西进行比较:

(@EmpOrfreeLance IS NULL
    OR IsEmployee IS NULL
    OR IsEmployee = @EmpOrfreeLance)

或者

ISNULL(IsEmployee, 0) = ISNULL(@EmpOrfreeLance, 0)

答案 1 :(得分:2)

我可能会遗漏一些东西,但为什么不写这样的查询?

SELECT distinct t1.UserId, tblCustomers.name 
FROM tblTime t1
inner join tblCustomers on t1.UserId=tblCustomers.custID
where sectionCat Like '%,35%' AND 
      ISNULL(IsEmployee, CAST(0 As bit)) = @EmpOrfreeLance

IsEmployee为空时,您还必须决定要做什么。 (是员工还是不是)例如,使用ISNULL(IsEmployee, CAST(0 As bit))来处理NULL值为false

答案 2 :(得分:0)

我错了,因为我错过了一件事

    SELECT distinct t1.UserId , tblCustomers.name 
    FROM tblTime t1
    inner join tblCustomers on t1.UserId=tblCustomers.custID
    where (t1.userid in (select distinct custID from tblCustomers where sectionCat Like '%,35%') )
    AND (t1.UserId in (select distinct custID from tblCustomers where IsEmployee = @EmpOrfreeLance))
AND (isActive = 1 AND isActiveAgent  = 1 AND sivug Like '%,35%' AND custType = 1) 
or (isActive  = 1 AND isActiveAgent  = 1 AND sivug Like '%,35%' AND custType = 3) 
or (isActive  = 1 AND isActiveAgent  = 1 AND sivug Like '%,35%' AND custType  between  5 AND 12 )

我不想显示所有数据而且我没有注意到在其他行上发出了一个OR

所以我不得不把它添加到那里