Stored procedure - Passing a parameter as xml and reading the data

孤者浪人 提交于 2020-01-15 09:13:58

问题


I have this stored procedure, that reads data from xml and make some inserts

ALTER procedure [dbo].[SP_InsertIOs] 
    @iosxml xml AS

DECLARE @currRecord int    

-- parse the records from the XML
  EXECUTE sp_xml_preparedocument @currRecord OUTPUT, @iosxml     
  BEGIN TRY       
   INSERT INTO SN_IO ( [C1] ,[C2]  ,[C3] )
   SELECT [C1] ,[C2] ,[C3]
   FROM OPENXML (@currRecord, 'ios/io', 1)
   WITH ([C1] [varchar](25)       'C1',
         [C2] [varchar](25)       'C2',
         [C3] [varchar](20)       'C3'  )                                                                  
    END TRY
    BEGIN CATCH
        //SELECT SOME ERROR
    END CATCH
    EXECUTE sp_xml_removedocument @currRecord

the xml looks like this

<ios>
  <io>
    <C1>a</C1>
    <C2>b</C2>
    <C3>c</C3>    
  </io>
  <io>
    <C1>x</C1>
    <C2>y</C2>
    <C3>z</C3>
  </io>
</ios>

Everything goes well. Sometimes C1 or C2 or C3 can be nulls and here are my questions:

In the procedure, when making the inserts if C1 is null or C2 is null or C3 is null skip that record and not make the insertion


回答1:


You just need a WHERE clause I think.

   INSERT INTO SN_IO ( [C1] ,[C2]  ,[C3] )
   SELECT [C1] ,[C2] ,[C3]
   FROM OPENXML (@currRecord, 'ios/io', 1)
   WITH ([C1] [varchar](25)       'C1',
         [C2] [varchar](25)       'C2',
         [C3] [varchar](20)       'C3'  )    
    WHERE  [C1]  IS NOT NULL  AND [C2]  IS NOT NULL AND [C3] IS NOT NULL  

Or you can do it in the XPath instead which I guess may be more efficient

   FROM OPENXML (@currRecord, 'ios/io[C1 and C2 and C3]', 1)


来源:https://stackoverflow.com/questions/3244796/stored-procedure-passing-a-parameter-as-xml-and-reading-the-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!