SQL对XML字段的操作

定义XML字段

create table FormAnswers(
  answerid int identity(1,1) not null,
  files xml null
)

files字段是XML字段,可能为NULL,不为null的时候,结构如下:


或者


  

假如我们想要查找所有附件个数大于1的数据,SQL如下:

select * from formanswers where convert(char(100),files.query('count(/package/file)'))>1

更多SQL对XML字段的操作可以参考文章 SQL对Xml字段的操作

select * from Answers where XmlFiles.value('count(/package/file)','int')>1

package的结构如下:


  
    

获取所有文件名为aaa的版本号:

SELECT ROW_NUMBER() OVER(partition BY ProjectID ORDER BY ORGRequestAnswerID ASC ) AS rid,a.ProjectID,
m.c.value('@name', 'varchar(max)') as name,
 m.c.value('@version', 'varchar(max)') as versionNum 
 FROM dbo.ORGRequestAnswers as a outer apply a.PackageXml.nodes('package/file') as m(c) WHERE DeletedDate IS NULL AND ObjectType='request' AND m.c.value('@name', 'varchar(max)') ='aaa'

data的结构如下:


  19年1月测试
  上海交通大学医学院附属第九人民医院
  11111
  口腔正畸科
  测试
  100
  100
  100
  
    
      a
      100
      
      
      
    
    
      b
      300
      
      
      
    
    
      c
      3100
      
      
      
    
  
  3500

获取所有id为Money的值

SELECT T2.lin.value('(td[@id="Money"])[1]', 'int') AS moneyAcount
FROM   (SELECT Result.query('data/question[@id="tblList"]') AS xmlSmartTable FROM dbo.BalanceRequestAnswers WHERE BalanceRequestID=(SELECT ObjectID FROM dbo.WorkflowInstances WHERE WorkflowInstanceID={0})) resultSmartTable
CROSS APPLY xmlSmartTable.nodes('/question/row') as T2(lin)

你可能感兴趣的:(SQL对XML字段的操作)