如何使用包含查询返回值的参数运行存储过程?
这就是我想要做的事情:
[dbo].[InsertMultiChoiceList] [PatientRiskAssessmentQuestionsID], [NetworkRiskAssessmentQuestionsID], Answer
// select query returning PatientRiskAssessmentQuestionsID, NetworkRiskAssessmentQuestionsID, Answer
选择查询可以返回多行。
答案 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),则最简单。然后,您可以INSERT
将SELECT
的结果导入#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;
(也可能INSERT
将SELECT
结果导入临时表或表变量,然后使用CURSOR
和WHILE
循环遍历该表中的每一行并在每次迭代时调用一次存储过程,但由于我尝试永远不使用游标,因此我没有使用游标的经验,也无法显示示例。)