Querying SQL Server xml column with user provided XPath via Entity Framework

后端 未结 2 1041
执念已碎
执念已碎 2021-01-05 22:25

I\'m having a really tough time figuring how to use an xml data column in SQL Server, specifically for use with Entity Framework.

Basically, one of our tables stores

2条回答
  •  温柔的废话
    2021-01-05 23:08

    You could do this in a stored procedure where you build your query dynamically.

    SQL Fiddle

    MS SQL Server 2008 Schema Setup:

    create table YourTable
    (
      ID int identity primary key,
      Name varchar(10) not null,
      XMLCol xml
    );
    
    go
    
    insert into YourTable values
    ('Row 1', '1'),
    ('Row 2', '2'),
    ('Row 3', '3');
    
    go
    
    create procedure GetIt
      @XPath nvarchar(100)
    as
    begin
      declare @SQL nvarchar(max);
    
      set @SQL = N'
      select ID, Name
      from YourTable
      where XMLCol.exist('+quotename(@XPath, '''')+N') = 1';
    
      exec (@SQL);
    end
    

    Query 1:

    exec GetIt N'*[text() = "2"]'
    

    Results:

    | ID |  NAME |
    --------------
    |  2 | Row 2 |
    

提交回复
热议问题