在WITH sql之后返回标量值

时间:2017-06-26 11:21:31

标签: sql sql-server

我想写一个返回0或1的函数。如果我在代码中使用WITH-construction那么该怎么做

ALTER FUNCTION [dbo].[IsBossFull] (@bossFull int, @user int)
RETURNS bit 
AS
BEGIN
          ;WITH CTE
            AS (
                    SELECT *
                    FROM [USERS] WHERE [Id] = @user
                    UNION ALL
                    SELECT U.*
                    FROM CTE C
                        INNER JOIN [USERS] u on U.[Id] = C.[Chief]
                )
                -- then something like
                if exists(
                select * from cte where id = @bossFull)
                return 1
                else return 0
END

1 个答案:

答案 0 :(得分:1)

您可以将值赋给变量并返回:

<div class="container">
  <div class="autogenerated-div">OOO</div>
  <div class="autogenerated-div">OOO</div>
  <div class="autogenerated-div">OOO</div>
  <div class="autogenerated-div">OOO</div>
  <div class="autogenerated-div">OOO</div>
  <div class="autogenerated-div">OOO</div>
  <div class="autogenerated-div">OOO</div>
  <div class="autogenerated-div">OOO</div>
</div>

我实际上并没有简化代码。您可以在实际找到DECLARE @retval int; WITH CTE AS ( SELECT * FROM USERS WHERE Id = @user UNION ALL SELECT U.* FROM CTE C INNER JOIN USERS u ON U.[Id] = C.[Chief] ) SELECT @retval = COUNT(*) FROM cte WHERE id = @bossfull; RETURN(@retval); 时停止递归。

如果您真的想要,可以使用@bossful。但是,return(case when retval > 0 then 1 else 0 end)不能大于1,因为这意味着层次结构中的循环 - 并且CTE不会返回。