Sql 如何将存储过程的结果插入到新表中
对于要计算countexel和scoreexel的给定staffid,可以将存储过程重新编写为:Sql 如何将存储过程的结果插入到新表中,sql,sql-server,Sql,Sql Server,对于要计算countexel和scoreexel的给定staffid,可以将存储过程重新编写为: ALTER procedure [dbo].[staffscorecard] @STAFF_ID INT = NULL as select count(STAFF_ID) as countexel from TbStudentSurvey where FEEDBACK = 'excellent'
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
然后不要使用临时表,而是使用表变量,因为在使用临时表时,表必须与存储过程中的精确列布局相匹配
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
方法2:
您也可以写为:
--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
希望这有帮助 你能解释清楚你的问题吗?我已经创建了一个存储过程,现在我想把这个过程插入一个新表中。我怎么做?如果你能使用一个表值函数,你可以在一个函数中这样做。使用表变量类型代替临时表。这看起来像是从dbo.myFunctionName(@StaffId)中选择*,它将返回一个值表。您可以使用表值函数,也可以将两列都放在一个select查询中,然后可以将输出插入到临时表中。SP只返回一个字段,而insert有两个字段。
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