views:

111

answers:

2

Hi,

What would be the most effective way to grab the schema + table name in this scenario:

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

The outcome needs to be: "SchemaName.TableName" ....

I'm using C#.

Thanks!

+1  A: 

Just some good old string parsing with Substrings would be my guess. Some code:

 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);
BFree
+1  A: 

Or you could use a regular expression:

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]); }

Or if you don't want to include the brackets:

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]); }
w4g3n3r
In addition you could extend regex to include JOINs and handle multiple whitespaces
PiRX