存储过程 - 将参数作为xml传递并读取数据

时间:2010-07-14 09:18:27

标签: sql sql-server sql-server-2005 tsql

我有这个存储过程,它从xml中读取数据并进行一些插入

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

xml看起来像这样

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

一切顺利。 有时C1或C2或C3可以为空,这是我的问题:

在程序中,当C1为空或C2为null或C3为空时进行插入时跳过该记录而不进行插入

1 个答案:

答案 0 :(得分:0)

我认为你只需要一个WHERE条款。

   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  

或者您可以在XPath中执行此操作,我认为可能更有效

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