TSQL How to select employee with skills in xml col

2019-07-04 14:53发布

问题:

In a table schema like below

CREATE TABLE [dbo].[Employee](
    [EmployeeId] [uniqueidentifier] NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
    [Location] [nvarchar](50) NOT NULL,
    [Skills] [xml] NOT NULL
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
  • How would i get Employees having C#(case insensitive) programming skills assuming the xml saved in the Skills columns is as below.

  • Could you advice on other functions would help me filter, sort when using xml data type columns

<Skills><Skill>C#</Skill><Skill>ASP.NET</Skill><Skill>VB.NET</Skill></Skills>

回答1:

The comparison is case sensitive so you need to compare against both c# and C#. In SQL Server 2008 you can use upper-case.

declare @T table
(
  ID int identity,
  Skills XML
)

insert into @T values
('<Skills><Skill>C#</Skill><Skill>ASP.NET</Skill><Skill>VB.NET</Skill></Skills>')
insert into @T values
('<Skills><Skill>CB.NET</Skill><Skill>ASP.NET</Skill><Skill>c#</Skill></Skills>')
insert into @T values
('<Skills><Skill>F#</Skill><Skill>ASP.NET</Skill><Skill>VB.NET</Skill></Skills>')

select ID
from @T
where Skills.exist('/Skills/Skill[contains(., "C#") or contains(., "c#")]') = 1

Result:

ID
-----------
1
2

Update:

This will also work.

select T.ID
from @T as T
  cross apply T.Skills.nodes('/Skills/Skill') as X(N)
where X.N.value('.', 'nvarchar(50)') like '%C#%'