sql server将存储过程转换为函数

时间:2016-12-20 05:22:28

标签: sql-server stored-procedures

我需要帮助将存储过程转换为函数

CREATE procedure [dbo].[procBedcount] @place nvarchar(50)
as 
begin
declare @Allbedrahia int;
declare @remain int;
declare @noOccupiedBeds int;
set @place='%' + @place +'%';
set @Allbedrahia =   (select [NopatientsBeds] from departments where Depname ='special')
set @noOccupiedBeds= (SELECT [noOccupiedBeds]   FROM [patientticket].[dbo].[CountsumRahia] );
set @remain = @Allbedrahia - @noOccupiedBeds;
--print ' this ' & @remain
(select depName,noOccupiedBeds,allbeds,remain from AllOccupiedBeds
where AllOccupiedBeds.buildplace like @place
union 
SELECT  [depname],[noOccupiedBeds],@Allbedrahia,@remain   FROM [patientticket].[dbo].[CountsumRahia])

end

结果必须是四列(depName,noOccupiedBeds,allbeds,retain)

例如

EXEC     [dbo].[procBedcount]
        @place = N'special'

返回(depName,noOccupiedBeds,allbeds,retain)列

1 个答案:

答案 0 :(得分:0)

只需制作一个表值函数:

   CREATE function [dbo].[funcBedCount]
   (
     @place nvarchar(50)
   )  

   RETURNS @tblReturn table 
   (
     depname nvarchar(50),
     noOccupiedBeds int,
     allbeds int,
     remain int
   )
   AS
   BEGIN

    -- Other initializations ...

    Insert Into @tblReturn (depname, noOccupiedBeds, allbeds, remain )
    (SELECT depName,noOccupiedBeds,allbeds,remain FROM AllOccupiedBeds
        WHERE AllOccupiedBeds.buildplace like @place
    UNION 
    SELECT  [depname],[noOccupiedBeds],@Allbedrahia,@remain 
    FROM [patientticket].[dbo].[CountsumRahia]) 

  END

 RETURN 
 GO