Sql Server查询中的案例条件冲突

时间:2012-05-23 05:50:30

标签: sql tsql sql-server-2005

select  CASE when  (select distinct BR.BorrowerID from tblBorrow BR 
inner join tblWorker W on W.ContractorID=BR.BorrowerID 
inner join  tblBorrowWorker TWB on  TWB.WorkerID=W.WorkerID 
inner join tblBorrowWorkerAssign TBWA on TWB.BorrowWorkerAssignmentID=TBWA.BorrowWorkerAssignmentID where TWB.WorkerID=11276) then 'BR.BorrowerID'   else 'NotBorrowed' end as BorrowedStatus

这里实际上在'Then'条件我想要显示BorrowerID,这里子查询部分运行良好并返回ID,但是当我添加CASE语句时它给出一个错误 “在预期条件的上下文中指定的非布尔类型的表达式,接近'then'。”此查询是我存储过程的一部分。将是解决方案

2 个答案:

答案 0 :(得分:1)

CASE子句需要一个布尔条件。你能用Exists()检查真实情况吗?尝试将exists()用于内部select语句(从select distinct BR.BorrowerID from tblBorrow BR...开始)

答案 1 :(得分:1)

如果您要从子查询中显示BR.BorrowerID的值而不是'BR.BorrowerID'字符串常量,则可以尝试以下操作(假设您已确保子查询返回的行数不超过一行):

SELECT
  ISNULL(
    (
      SELECT DISTINCT CAST(BR.BorrowerID AS varchar(15))
      FROM tblBorrow BR 
      INNER JOIN tblWorker W ON W.ContractorID = BR.BorrowerID 
      INNER JOIN tblBorrowWorker TWB ON TWB.WorkerID = W.WorkerID 
      INNER JOIN tblBorrowWorkerAssign TBWA ON TWB.BorrowWorkerAssignmentID = TBWA.BorrowWorkerAssignmentID
      WHERE TWB.WorkerID=11276
    ),
    'NotBorrowed'
  )

另一方面,如果这是您帖子中的完整查询(不是较大查询的一部分),则以下也可能是一个选项:

SELECT DISTINCT ISNULL(CAST(BR.BorrowerID AS varchar(15)), 'NotBorrowed')
FROM
    (SELECT 1) x (x)
    LEFT JOIN
        tblBorrow BR 
        INNER JOIN tblWorker W ON W.ContractorID = BR.BorrowerID 
        INNER JOIN tblBorrowWorker TWB ON TWB.WorkerID = W.WorkerID 
        INNER JOIN tblBorrowWorkerAssign TBWA ON TWB.BorrowWorkerAssignmentID = TBWA.BorrowWorkerAssignmentID
    ON TWB.WorkerID = 11276

(SELECT 1) x (x)“表”仅用于确保在左连接的右侧没有返回任何行的情况下结果集不为空。