请注意,使用综合查询解析器可能会更好,但它确实回答了您的问题。
VB.net
公共共享函数 GetTableName(query As String) As String Dim tableName = String.Empty
Dim fromPos = query.IndexOf(" FROM", StringComparison.OrdinalIgnoreCase)
If fromPos = -1 Then
Return tableName
End If
tableName = query.Substring(fromPos + 6)
' check if there is a schema
If tableName.IndexOf("] ", StringComparison.Ordinal) = -1 Then
' query does not contain [dbo].[tableName] schema
tableName = tableName.Substring(0, tableName.IndexOf(" ", StringComparison.Ordinal))
Else
' query contains some form of schema
tableName = tableName.Substring(0, tableName.IndexOf("] ", StringComparison.Ordinal) + 1)
End If
Return tableName
结束功能
C#
public static string GetTableName(string query)
{
var tableName = string.Empty;
var fromPos = query.IndexOf(" FROM", StringComparison.OrdinalIgnoreCase);
if (fromPos == -1)
{
return tableName;
}
tableName = query.Substring(fromPos + 6);
// check if there is a schema
if (tableName.IndexOf("] ", StringComparison.Ordinal) == -1)
{
// query does not contain [dbo].[tableName] schema
tableName = tableName.Substring(0, tableName.IndexOf(" ", StringComparison.Ordinal) );
}
else
{
// query contains some form of schema
tableName = tableName.Substring(0, tableName.IndexOf("] ", StringComparison.Ordinal) + 1);
}
return tableName;
}
测试
GetTableName("fkgsejrtlekrjgsdlkfgjsdfg")
// Returns Empty string
GetTableName("SELECT * FROM _table WHERE column LIKE '%test%"))
// Returns _table
GetTableName("SELECT * FROM SomeReallyReallyLongTableName WHERE column LIKE '%test%"))
// Returns SomeReallyReallyLongTableName
GetTableName("SELECT * FROM [dbo].[My Table] WHERE column LIKE '%test%"))
// Returns [dbo].[My Table]