t-SQL - 如何解析特定文本的条目

时间:2014-07-22 19:41:56

标签: sql sql-server tsql

我有一个需要搜索的数据库,里面装满了windows事件日志条目。

具体来说,我只需要返回一部分事件消息(以下示例中的“帐户名称:John”)。不幸的是,这必须使用SQL来完成,并且没有字符串开始或结束的设置字符,并且“John”部分可以是活动目录中的任何名称。 这似乎有点像Regex的工作,但我希望可能有一个我想念的替代品。

A user account was locked out.
Subject:
   Security ID:  SYSTEM
   Account Name:  WIN-R9H529RIO4Y$
   Account Domain:  WORKGROUP
   Logon ID:  0x3e7
Account That Was Locked Out:
   Security ID:  WIN-R9H529RIO4Y\John
   Account Name:  John
Additional Information:
Caller Computer Name: WIN-R9H529RIO4Y

思想?

1 个答案:

答案 0 :(得分:0)

这可能不是解决问题的最有效方法,但似乎确实有效。

我故意将其冗长,以便可以理解,但如果您愿意,可以轻松地将其简化为单一陈述:

declare @string varchar(max) = 
'A user account was locked out.
Subject:
   Security ID:  SYSTEM
   Account Name:  WIN-R9H529RIO4Y$
   Account Domain:  WORKGROUP
   Logon ID:  0x3e7
Account That Was Locked Out:
   Security ID:  WIN-R9H529RIO4Y\John
   Account Name:  John
Additional Information:
Caller Computer Name: WIN-R9H529RIO4Y';

declare @AccountStartIndex int = 
    len(@string) - charindex(reverse('Account Name:  '), reverse(@string));
declare @AccountEndIndex int = 
    charindex(char(13) + char(10), @string, @AccountStartIndex);

select substring(
    @string, 
    @AccountStartIndex + 2, 
    @AccountEndIndex - @AccountStartIndex - 1);

它的工作原理是在字符串中找到Account Name:的最后一次出现,然后计算出跟随它的换行符的位置。通过这两条信息,我们可以将John子串出来。

相关问题