我有两个sprocs用于赋值,我要做的是将xml输出从一个sproc传递到另一个sproc并将它放在一个变量中,我知道ex1.xml_sp1在用{{调用它时返回一个int 1}}并且显然在尝试选择它时它返回null,因为EXEC
是xml数据类型。
我想要做的是检索sproc 1中的xml数据并将其存储到sproc 2中的@x
。
有没有办法做到这一点?
sproc 1:
@x
sproc 2:
ALTER PROC [ex1].[xml_sp1]
@careteamid int
as
select CareTeams.CareTeamID, Doctors.DoctorID, Doctors.DoctorName,
CareTeamDoctors.DateJoined, CareTeamDoctors.CurrentMember
from dbo.CareTeamTbl as CareTeams
inner join dbo.CareTeamDoctorTbl as CareTeamDoctors on
CareTeams.CareTeamID = CareTeamDoctors.CareTeamID
inner join dbo.DoctorTbl as Doctors on
CareTeamDoctors.DoctorID=CareTeamDoctors.DoctorID
where CareTeamDoctors.CareTeamID = @careteamid
and CareTeamDoctors.DoctorID = Doctors.DoctorID
for xml auto, root('thedata')
答案 0 :(得分:3)
我想做的是检索并将sproc 1中的xml数据存储到sproc 2中的@x。
您可以使用OUTPUT
parameters
CREATE PROCEDURE [xml_sp1]
@careteamid INT,
@xml_output XML OUTPUT
AS
BEGIN
SET @xml_output = (SELECT * FROM ... FOR XML AUTO, root('thedata'));
END;
GO
CREATE PROCEDURE [xml_sp2]
@careteamid INT
AS
BEGIN
DECLARE @x XML;
EXEC [xml_sp1]
@careteamid,
@x OUTPUT;
SELECT @x AS XMLData;
END;
GO
最后的电话:
EXEC [xml_sp2] @careteamid = 1;
的 LiveDemo
强>
考虑使用BEGIN/END
阻止并使用;
结束每个语句,以避免可能出现的问题。
可能的共享数据方法的完整列表 How to Share Data between Stored Procedures by Erland Sommarskog
答案 1 :(得分:3)
对于返回值(即EXEC @ReturnValue = StoredProcName...;
),INT
是唯一允许的数据类型。如果这需要真正保留为存储过程,那么您可以使用OUTPUT
变量或在第二个存储过程中创建临时表或表变量并执行INSERT INTO ... EXEC StoredProc1;
。
但是,鉴于第一个存储过程仅执行一个简单的SELECT语句,您最好将其转换为内联表值函数(iTVF),如下所示:
CREATE FUNCTION dbo.GetData (@CareTeamID INT)
RETURNS TABLE
AS RETURN
SELECT tab.col AS [CareData]
FROM (
SELECT CareTeams.CareTeamID, Doctors.DoctorID, Doctors.DoctorName,
CareTeamDoctors.DateJoined, CareTeamDoctors.CurrentMember
FROM dbo.CareTeamTbl as CareTeams
INNER JOIN dbo.CareTeamDoctorTbl as CareTeamDoctors
ON CareTeams.CareTeamID = CareTeamDoctors.CareTeamID
INNER JOIN dbo.DoctorTbl as Doctors
ON CareTeamDoctors.DoctorID=CareTeamDoctors.DoctorID
WHERE CareTeamDoctors.CareTeamID = @CareTeamID
AND CareTeamDoctors.DoctorID = Doctors.DoctorID
FOR XML AUTO, ROOT('thedata'), TYPE -- "TYPE" causes result to be XML and not NVARCHAR
) tab(col);
然后只需将第二个存储过程更改为:
SELECT care.CareData AS [XMLData]
FROM dbo.GetData(@CareTeamID);
或者,如果您确实需要在第二个存储过程中使用该XML数据,请执行以下操作:
DECLARE @TempData XML;
SELECT @TempData = care.CareData
FROM dbo.GetData(@CareTeamID);
最后,如果您需要XML数据实际上是来自该iTVF的XML数据类型(或者即使您将其保存为存储过程),那么您需要将TYPE
选项添加到FOR XML
子句,否则返回的是字符串/ NVARCHAR(MAX)
:
FOR XML AUTO, ROOT ('thedata'), TYPE
答案 2 :(得分:2)
为什么不试试这个而不是直接分配sp1的输出
declare @t table
(
val xml
)
insert into @t
exec ex1.xml_sp1
@careteamid = @careteamid
select * from @t
答案 3 :(得分:-1)
这会有用吗?
Original String: $1 $2 $3 $4
should be replaced with
New String: $2 $3 $1 $4
然后将该变量传递给另一个sproc?
我从这里回答
How to insert FOR AUTO XML result into table?。
在我看来,这个想法是相似的,或者应该是类似的。