2014-07-22 50 views
0

我有一個數據庫,我需要搜索充滿了Windows事件日誌條目。t-SQL - 如何解析特定文本的條目

具體來說,我只需要返回一部分事件消息(下面例子中的'Account Name:John')。不幸的是,這必須用SQL來完成,並且沒有字符串開始或結束的設置字符,'John'部分可以是活動目錄中的任何名稱。 這似乎更像是一個正則表達式的工作,但我希望可能有一個替代方案,我錯過了。

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

你可能想看看這個[問題](http://stackoverflow.com/questions/2647/how-do-i-split-a-string-so-i-can-access-item -x) – Becuzz

回答

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列出。

+0

謝謝先生。這種冗長的添加真的有幫助! – zackm