使用查询返回的结果执行存储过程

时间:2017-05-06 17:17:30

标签: sql sql-server stored-procedures

如何使用包含查询返回值的参数运行存储过程?

这就是我想要做的事情:

[dbo].[InsertMultiChoiceList]  [PatientRiskAssessmentQuestionsID],  [NetworkRiskAssessmentQuestionsID], Answer

// select query returning PatientRiskAssessmentQuestionsID, NetworkRiskAssessmentQuestionsID, Answer

选择查询可以返回多行。

1 个答案:

答案 0 :(得分:0)

您的问题的答案取决于SELECT查询是否始终只返回一行,或者可能超过1行。

SELECT只返回一行:

然后,您可以将三列值放入变量并将它们传递给存储过程:

DECLARE @patientRiskAssessmentQuestionsID INT;
DECLARE @networkRiskAssessmentQuestionsID INT;
DECLARE @answer NVARCHAR(…);

SELECT TOP(1)
       @patientRiskAssessmentQuestionsID = [PatientRiskAssessmentQuestionsID]
     , @networkRiskAssessmentQuestionsID = [NetworkRiskAssessmentQuestionsID]
     , @answer = [Answer]
FROM …
WHERE …;

EXECUTE [dbo].[InsertMultiChoiceList] @patientRiskAssessmentQuestionsID
                                    , @networkRiskAssessmentQuestionsID
                                    , @answer;

SELECT可能返回多行:

在这种情况下,如果您的存储过程不接受三个标量值,而是单个table-valued parameter (TVP),则最简单。然后,您可以INSERTSELECT的结果导入#temporaryTable@tableVariable并将其传递给您的存储过程:

-- You'd create the following table type once and make the parameter
-- of your stored procedure be of this type:

--CREATE TYPE [dbo].[SelectionTableType] AS TABLE
--(
--    [PatientRiskAssessmentQuestionsID] INT
--   ,[NetworkRiskAssessmentQuestionsID] INT
--   ,[Answer] NVARCHAR(…)
--);

DECLARE @selection AS [dbo].[SelectionTableType];

INSERT INTO @selection ([PatientRiskAssessmentQuestionsID], [NetworkRiskAssessmentQuestionsID], [Answer])
SELECT [PatientRiskAssessmentQuestionsID]
     , [NetworkRiskAssessmentQuestionsID]
     , [Answer]
FROM …
WHERE …;

EXECUTE [dbo].[InsertMultiChoiceList] @selection;

(也可能INSERTSELECT结果导入临时表或表变量,然后使用CURSORWHILE循环遍历该表中的每一行并在每次迭代时调用一次存储过程,但由于我尝试永远不使用游标,因此我没有使用游标的经验,也无法显示示例。)