以下xml属于xml列AuditData。我想查询其中包含'Blondie'的所有记录。
<AuditText Username="Blondie" CustomerGUID="xxxxxxxxxx3C4B35821FC0" IPAddress="xx.xxx.xxx.xx" />
我正在尝试这个无效的查询...
select top 10 * from t_audit (nolock)
and AuditData.value('(/Username)[1]','varchar(max)') like 'Blondie'
答案 0 :(得分:2)
我想有几个AuditText节点,其中一些属于Blondie?
您可以粉碎完整的XML,并使用类似表格的数据在经典keytool -exportcert -keystore YOUR_PATH_HERE/.android/debug.keystore | PATH_TO_BIN_FOLDER_OF_SSL_DIRECTORY_IN_C:/openssl.exe sha1 -binary | PATH_TO_BIN_FOLDER_OF_SSL_DIRECTORY_IN_C:/openssl.exe base64
子句中使用LIKE
对其进行过滤。但更好的是WHERE
。最好使用XQuery
方法,但您也可以使用.nodes()
甚至.query()
。
在这个例子中,我添加了一个根节点和几个测试节点:
.value()
如果要在AuditTable中搜索行,可以使用DECLARE @xml XML=
'<root>
<AuditText Username="Blondie" CustomerGUID="xxxxxxxxxx3C4B35821FC0" IPAddress="xx.xxx.xxx.xx" />
<AuditText Username="Test1" CustomerGUID="xxxxxxxxxx11111111" IPAddress="xx.xxx.111.11" />
<AuditText Username="Blondie" CustomerGUID="xxxxxxxxxx3C4B35821FC0" IPAddress="xx.xxx.xxx.xx" />
<AuditText Username="Test2" CustomerGUID="xxxxxxxxxx222222222" IPAddress="xx.xxx.222.22" />
</root>
';
SELECT Blondie.value('@CustomerGUID','varchar(max)') AS CustomerGuid --you might set the type to "uniqueidentifier", if the value is a valid GUID
FROM @xml.nodes('/root/AuditText[@Username="Blondie"]') AS Only(Blondie);
--This is the way to insert your search string via variable
DECLARE @Username VARCHAR(100)='Test1';
SELECT MyUser.value('@CustomerGUID','varchar(max)')
FROM @xml.nodes('/root/AuditText[@Username=sql:variable("@Username")]') AS Only(MyUser);
:
.exist()
最后,如果您的XML 格式不正确,您可能只是使用
进行过滤CREATE TABLE #t_audit(ID INT IDENTITY,AuditData XML);
INSERT INTO #t_audit(AuditData) VALUES
('<AuditText Username="Blondie" CustomerGUID="xxxxxxxxxx3C4B35821FC0" IPAddress="xx.xxx.xxx.xx" />')
,('<AuditText Username="Blondie" CustomerGUID="xxxxxxxxxx3C4B35821FC0" IPAddress="xx.xxx.xxx.xx" />')
,('<AuditText Username="Test1" CustomerGUID="xxxxxxxxxx11111111" IPAddress="xx.xxx.111.11" />')
,('<AuditText Username="Blondie" CustomerGUID="xxxxxxxxxx3C4B35821FC0" IPAddress="xx.xxx.xxx.xx" />')
,('<AuditText Username="Test2" CustomerGUID="xxxxxxxxxx222222222" IPAddress="xx.xxx.222.22" />');
SELECT *
FROM #t_audit
WHERE AuditData.exist('AuditText[@Username="Blondie"]')=1;
--DROP TABLE #t_audit;
或(更准确地说)
WHERE CAST(AuditData AS VARCHAR(MAX)) LIKE '%Blondie%'