TSQL How to select employee with skills in xml col

2019-07-04 15:02发布

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条回答
劫难
2楼-- · 2019-07-04 15:24

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#%'
查看更多
登录 后发表回答