-5

我可以有

PROCEDURE dbo._ws_CallLogs_DeleteAll

或者

TABLE [dbo].[CachedPlan]

或者

VIEW [test].[MyView]

或者

FUNCTION [xyz].[ParseStringList]

作为输入

输出应该是

对于案例 1

string Type =  PROCEDURE
string DBOName = dbo
string obejctName = _ws_CallLogs_DeleteAll 

对于案例 2

string Type =  TABLE
string DBOName = dbo
string obejctName = CachedPlan 

对于案例 3

string Type = VIEW
string DBOName = test
string obejctName = MyView 

对于案例 4

string Type =  FUNCTION
string DBOName = xyz
string obejctName = ParseStringList

怎么做?

4

2 回答 2

2

这是另一种解析方式:

static void Main(string[] args)
{
    var parser = new TSql100Parser(true);
    IList<ParseError> errors = new List<ParseError>();
    using (TextReader r = new StreamReader("sql.txt"))
    {
        var result = parser.GetTokenStream(r, errors);
        var results = result
            .Select((i, index) => (i.TokenType == TSqlTokenType.Create) ? index : -1)
            .Where(i => i >= 0)
            .Select(i => result.Skip(i + 1).TakeWhile(j =>
                (j.TokenType == TSqlTokenType.WhiteSpace
                || j.TokenType == TSqlTokenType.QuotedIdentifier
                || j.TokenType == TSqlTokenType.Identifier
                || j.TokenType == TSqlTokenType.Dot
                || j.TokenType == TSqlTokenType.Table
                || j.TokenType == TSqlTokenType.Procedure
                || j.TokenType == TSqlTokenType.View
                || j.TokenType == TSqlTokenType.Function
                ))
                .Where(j => (j.TokenType != TSqlTokenType.WhiteSpace 
                    && j.TokenType != TSqlTokenType.Dot))
                );

        foreach (var item in results)
        {
            var type = item.Where(i => (i.TokenType != TSqlTokenType.QuotedIdentifier
                || i.TokenType != TSqlTokenType.Identifier));
            Console.WriteLine("Type: {0}\tDbo: {1}\tObject: {2}",
                type.First().Text,
                type.Skip(1)
                    .Take(type.Count() - 2)
                    .Aggregate<TSqlParserToken, string>("", 
                        (a, b) => a + ((a == "") ? "" : ".") + b.Text),
                type.Last().Text);
        }
    }
}

您需要对以下命名空间的必需引用:

using Microsoft.Data.Schema.ScriptDom.Sql;
using Microsoft.Data.Schema.ScriptDom;
于 2013-05-14T12:44:33.553 回答
0

只要输入格式相同,您就可以使用此正则表达式。

(?<type>PROCEDURE|TABLE|VIEW|FUNCTION)\s+\[?(?<name>\w+)\]?[.]\[?(?<object>\w+)\]?

现在你可以得到这样的比赛

Match m=Regex.Match(input,regex,RegexOptions.IgnoreCase);
m.Groups["type"].Value;//type
m.Groups["name"].Value;//name
m.Groups["object"].Value;//object
于 2013-05-14T10:32:28.327 回答