在以下字符串中获取表名的最有效方法

时间:2008-12-10 02:35:44

标签: c# string

在这种情况下,获取模式+表名的最有效方法是什么:

SELECT [t0]。[Id],[t0]。[CODE] AS [arg0],[t0]。[DESC] AS [arg1] FROM [SchemaName]。[TableName] AS [t0] WHERE([t0]。[Id]<> @ p0)

结果必须是:“SchemaName.TableName”....

我正在使用C#。

谢谢!

2 个答案:

答案 0 :(得分:1)

使用Substrings进行一些好的旧字符串解析将是我的猜测。一些代码:

 string q = @"SELECT [t0].[Id], [t0].[CODE] AS [arg0], [t0].[DESC] AS [arg1] FROM [SchemaName].[TableName] AS [t0] WHERE ([t0].[Id] <> @p0)";
            int fromIndex = q.IndexOf("FROM")+5;
            int asIndex = q.IndexOf("AS",fromIndex);
            q = q.Substring(fromIndex, asIndex - fromIndex);

答案 1 :(得分:1)

或者您可以使用正则表达式:

string data = "SELECT [t0].[Id], [t0].[CODE] AS [arg0], [t0].[DESC] AS [arg1] FROM [SchemaName].[TableName] AS [t0] WHERE ([t0].[Id] <> @p0)";
Regex re = new Regex(@"FROM ((\[\w+\]\.?){2}) AS");
Match m = re.Match(data);
if (m.Success){ Console.WriteLine(m.Groups[1]); }

或者如果您不想包含括号:

string data = "SELECT [t0].[Id], [t0].[CODE] AS [arg0], [t0].[DESC] AS [arg1] FROM [SchemaName].[TableName] AS [t0] WHERE ([t0].[Id] <> @p0)";
Regex re = new Regex(@"FROM \[(\w+)\]\.\[(\w+)\]\ AS");
Match m = re.Match(data);
if (m.Success){ Console.WriteLine("{0}.{1}", m.Groups[1], m.Groups[2]); }
豫ICP备18024241号-1