-2

My String/Query looks like this

  1. insert into Employee Values(1,2,'xxx');
  2. update Employee2 set col1='xxx' where col2='yyy';
  3. select * from Employee3;

I need to take/have TableName alone. Table name won't be constant it will be differed(Employee,Employee2,Employee3) according to DB. I'm new to C# please help me. Thanks in advance.

4

1 回答 1

0

要从查询中获取表的名称(或者在本例中为名为 'sql' 的字符串),请尝试以下操作:

        string sql = "select * from table ";
        int index1 = 0;
        int index2 = 0;
        int currentIndex = 0;
        int numSpaces = 0;
        char[] chArray = sql.ToCharArray();
        foreach (char c in chArray)
        {
            if (c == ' ')
            {
                numSpaces++;
                if (numSpaces == 3)
                    index1 = currentIndex;
                if (numSpaces == 4)
                {
                    index2 = currentIndex;
                    break;
                }
            }
            currentIndex++;
        }
        int length = index2 - index1;
        string tableName = sql.Substring(index1, length);
        MessageBox.Show(tableName);

警告 - 此解决方案基于查找第 3 和第 4 个空格字符之间的单词。这限制了您拥有一个非常可预测的查询结构 - 更复杂的查询可能不适用于此解决方案。您的查询结构需要是:

"select column_name1,column_name2,column_name3 from table "

您的查询在列之间不能有空格,并且最后也必须有空格。抱歉有限制,但这是我能想到的最好的;)

于 2013-03-13T11:26:20.420 回答