1

I have a requirement that i want to search for data in xml data type, from the front end i will get firstname,lastname,dob,email all the fields are not mandatory some fields will come as empty or null i want to search according to that if i will get firstname as 'test' and lastname i will get as empty or null

If it is a varchar datatype then i can create query as

FirstName= ISNULL(@firstname, FirstName) or COALESCE(@firstname, FirstName, '') = '')

but in XML doc how can i use this type of query.

xmlDoc.value('(/personalDetails/firstname)[1]','varchar(100)')

Thanks

4

2 回答 2

0

在 SQLServer 2008 中,我会写如下内容:

select 
    xmlDoc.value('(personalDetails/firstname/text())[1]','varchar(100)') as firstname 
from 
    myTable 
where 
    not xmlDoc is null
    and xmlDoc.exist('personalDetails/firstname[.!='''']')>0

如果你想为不存在的值返回 NULL,你也可以做一个 CASE WHEN ... ELSE ... END

于 2012-04-10T16:17:06.150 回答
0

我认为您可以使用公用表表达式来实现这一点。PFB示例代码-

DECLARE @XMLData XML
SET @XMLData ='
<STUDENTS>
  <STUDENT>
    <StudentID>1</StudentID>
    <Name>John Smith</Name>
    <Marks>200</Marks>
  </STUDENT>
  <STUDENT>
    <StudentID>2</StudentID>
    <Name>Mark Johnson</Name>
    <Marks>300</Marks>
  </STUDENT>
<STUDENT>
    <StudentID>3</StudentID>
    <Name></Name>
    <Marks>400</Marks>
  </STUDENT>
</STUDENTS>'
;with cte as(
SELECT StudentID = Node.Data.value('(StudentID)[1]', 'INT')
        , [Name] = Node.Data.value('(Name)[1]', 'VARCHAR(MAX)')
        , [Marks] = Node.Data.value('(Marks)[1]', 'INT')
FROM    @XMLData.nodes('/STUDENTS/STUDENT') Node(Data)
)
Select * from cte where Name=''
于 2019-09-04T06:29:22.583 回答