我正在使用SQL Server 2012中的存储过程中的OPENXML读取XML数据。
我的XML:
<name>
<name>Temp1</name>
<data>
<mealID>5</mealID>
<food>
<foodID>11</foodID>
</food>
<food>
<foodID>12</foodID>
</food>
</data>
<data>
<mealID>6</mealID>
<food>
<foodID>13</foodID>
</food>
</data>
</name>
我的存储过程:
ALTER PROCEDURE [dbo].[sp_Insert_EatingProgramTemplate]
@Template xml,
@intOutSuccess nvarchar(10) OUTPUT,
@ErrorSeverity nvarchar(MAX) OUTPUT,
@ErrorMesg nvarchar(MAX) OUTPUT
AS
BEGIN
DECLARE @idoc int
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SET @ErrorSeverity = ''
SET @ErrorMesg = ''
SET @intOutSuccess = ''
BEGIN TRY
SELECT *
FROM OPENXML (@idoc, '/ROOT/Customer',1)
WITH (CustomerID varchar(10),
ContactName varchar(20))
SET @intOutSuccess = 1
END TRY
BEGIN CATCH
SET @ErrorSeverity = ERROR_SEVERITY()
SET @ErrorMesg = ERROR_MESSAGE()
SET @intOutSuccess = -1
GOTO A
END CATCH
A:
END
GO
执行此程序时,我收到此错误:
无法找到带句柄0的预准备语句
任何帮助,为什么我收到此错误?
答案 0 :(得分:2)
您错过了通过调用@idoc
设置sp_xml_preparedocument
,例如:
declare @template xml = '<name>
<name>Temp1</name>
<data>
<mealID>5</mealID>
<food>
<foodID>11</foodID>
</food>
<food>
<foodID>12</foodID>
</food>
</data>
<data>
<mealID>6</mealID>
<food>
<foodID>13</foodID>
</food>
</data>
</name>'
DECLARE @idoc int
EXEC sp_xml_preparedocument @idoc OUTPUT, @template;
SELECT *
FROM OPENXML (@idoc, '/name/data/food/foodID',1)
WITH (FoodID INT '.',
MealID INT '../../mealID')
--clear parsed XML document from SQL Server cache
EXEC sp_xml_removedocument @idoc;
您也可以通过直接查询xml变量来实现相同的输出:
SELECT
x.value('.', 'int') as FoodID
, x.value('../../mealID[1]', 'int') as MealID
FROM @template.nodes('/name/data/food/foodID') as T(X)