如何将存储过程的结果插入到新表中

时间:2013-12-18 06:47:13

标签: sql sql-server

ALTER procedure [dbo].[staffscorecard] 
    @STAFF_ID INT = NULL
as 
    select 
        count(STAFF_ID) as countexel 
    from 
        TbStudentSurvey 
    where 
        FEEDBACK = 'excellent' 
        and STAFF_ID = ISNULL(@STAFF_ID, STAFF_ID)

    select 
        Score as scoreexel 
    from 
        TbStaffScoreMaster 
    where 
        Status = 'Excellent' 

    exec [dbo].[staffscorecard]
GO

CREATE TABLE #temp ( countexel int, scoreexel int)
GO

INSERT INTO #temp (countexel , scoreexel)
   EXEC [dbo].[staffscorecard]
GO

SELECT *
FROM #temp
GO

1 个答案:

答案 0 :(得分:0)

对于给定的职员来计算countexel和scoreexel,您可以将您的存储过程重写为:

create table TbStudentSurvey (STAFF_ID int,FEEDBACK varchar(20));
insert into TbStudentSurvey values (1,'excellent'),(1,'excellent'),(2,'excellent');
create table TbStaffScoreMaster (Score int,[Status] varchar(20));
insert into TbStaffScoreMaster values(100,'Excellent');
Go

create procedure [dbo].[staffscorecard] 
    @STAFF_ID INT = NULL,
    @countexel int output,-- Explicitly declare output variables to fetch these values
    @scoreexel int output
as 
Begin 
    select 
        @countexel = count(STAFF_ID) 
    from 
        TbStudentSurvey 
    where 
        FEEDBACK = 'excellent' 
        and STAFF_ID = ISNULL(@STAFF_ID, STAFF_ID)

    select 
        @scoreexel = Score  
    from 
        TbStaffScoreMaster 
    where 
        Status = 'Excellent' 
End
GO

然后使用临时表而不是使用临时表,因为当您使用临时表时,该表必须与存储过程中的确切列布局相匹配。

--CREATE TABLE #temp (countexel int, scoreexel int)
--GO
--Create a table variable:
declare @temp table (countexel int, scoreexel int)
declare @countexel int, @scoreexel int,@STAFF_ID int;
--set value of staff Id for which you want to get countexel and scoreexel.
set @STAFF_ID = 1;
EXEC [dbo].[staffscorecard] @STAFF_ID ,@countexel output,@scoreexel output
INSERT @temp values (@countexel ,@scoreexel);

SELECT *
FROM @temp
GO

方法2: 您也可以写为:

alter procedure [dbo].[staffscorecard] 
    @STAFF_ID INT = NULL    
as 
Begin 
    select 
        count(STAFF_ID) as countexel , Score as scoreexel
    from 
        TbStudentSurvey TSS
        inner join TbStaffScoreMaster TSM on TSM.Status = TSS.FEEDBACK 
    where 
        FEEDBACK = 'excellent' 
        and STAFF_ID = ISNULL(@STAFF_ID, STAFF_ID)   
     group by STAFF_ID,Score
End
GO

declare @temp table (countexel int, scoreexel int)
declare @STAFF_ID int;
set @STAFF_ID = 1;--set value of staff Id for which you want to get countexel and scoreexel.
INSERT @temp EXEC [dbo].[staffscorecard] @STAFF_ID 

SELECT *
FROM @temp
GO

希望这会有所帮助!!