Вопрос

in an column of xml data type, that contain the following structure, i want to find table rows where v like '%a%'

<PostVar>
  <d n="A" v="abc" />
  <d n="B" v="def" />
  <d n="C" v="ghi" />
  <d n="D" v="jkl" />
  <d n="E" v="mno" />
  <d n="F" v="pqr" />
</PostVar>

i used to work with a different xml type :-

<EVENT_INSTANCE>
  <EventType>ALTER_TABLE</EventType>
  <PostTime>2011-09-28T11:47:52.597</PostTime>
  <SPID>105</SPID>
  <ServerName>srv</ServerName>
  <LoginName>sa</LoginName>
  <UserName>dbo</UserName>
  <DatabaseName>server</DatabaseName>
  <SchemaName>tim</SchemaName>
  <ObjectName>_SystemTableVersion</ObjectName>
  <ObjectType>TABLE</ObjectType>
  <TSQLCommand>
    <SetOptions ANSI_NULLS="ON" ANSI_NULL_DEFAULT="ON" ANSI_PADDING="ON" QUOTED_IDENTIFIER="ON" ENCRYPTED="FALSE" />
    <CommandText>ALTER TABLE tim._SystemTableVersion ADD
resr datetime NULL
</CommandText>
  </TSQLCommand>
</EVENT_INSTANCE>

and SQL i use to "extract" data is :-

SELECT
    [ID]
    ,[EventData].value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]', 'nvarchar(max)')
    , ServerName, ServiceName, RemServer, SUserName, HostName, UserName, SUserSName, SystemUser, SessionUser, OriginalLogin, RecTime
FROM
    dbo.myTable
WHERE
    [EventData].value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]', 'nvarchar(max)')
        LIKE '%wordImLookingFor%'

any help would be appreciated.

Это было полезно?

Решение

You can use exist() and contains().

where XMLCol.exist('/PostVar/d/@v[contains(., "a")]') = 1

The comparison is however always case sensitive.

If you need to check against a variable you should use sql:variable().

declare @v varchar(10)
set @v = 'a'

select *
from YourTable
where XMLCol.exist('/PostVar/d/@v[contains(., sql:variable("@v"))]') = 1

Другие советы

I think the following will help:

select * -- your select list here  
  from mySchema.myTable -- your schema and table name here  
    where myColumn.value('(/PostVar/d/@v)[1]', 'nvarchar(3)') Like '%a%'  

Note: Since you did not specify the definition for the new table, you need to replace mySchema, myTable and myColumn to match your scenario.

The following link provides a good reference:
http://technet.microsoft.com/en-us/library/ms178030.aspx

Regards.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top