代码之家  ›  专栏  ›  技术社区  ›  ryanulit

从DB2表中选择并插入到SQL表中

  •  0
  • ryanulit  · 技术社区  · 16 年前

    我觉得这可能是一个疯狂的问题,如果有人对如何做有更好的想法,无论如何请告诉我。

    我在工作中有一个.NET C项目,它根据公司必须遵守的标准来验证某些表。这些表可以在SQL Server或DB2上。当一个表最初被添加到程序中时,我使用其中任何一个的select语句收集关于该表的元数据/信息。 information_schema.columns 对于SQL,或 syscat.columns 对于DB2。一旦我得到数据,我就把它存储在一个表中(我们称之为 all_table_information )在包含程序中验证的每个表的相同信息的SQL Server上。

    如果该表是SQL表,则可以运行此查询(当然,只能将其限制为所需表中的列):

    insert into [all_table_information]
        (table_id, column_name, data_type, max_char_length)
    select table_id, column_name, data_type, character_maximum_length
        from information_schema.columns 
        where ...restrict to needed table...
    

    然后在sqlcommand中执行。但是如果它是DB2表,我必须运行这个查询(再次限制到我需要的列):

    select tabschema, tabname, colname, typename, length 
    from syscat.columns 
    where ...restrict to needed table...
    

    然后获取包含结果的DataReader,并通过它循环插入每一行,使用:

    while (dr.Read())
    {
       insert into [all_table_information]
       (table_id, column_name, data_type, max_char_length) values 
       (..."'" + dr["whatever"] + "', '" + ....)
    
       ...execute sql here...
    
    } 
    dr.Close();
    

    这样做是可行的,但很慢,所以我想知道在一个声明中是否有这样的做法?我知道您也可以将DB2表信息保存到数据表中,但是您可以直接对数据表运行查询吗?

    谢谢, 赖安

    3 回复  |  直到 16 年前
        1
  •  1
  •   Steven    16 年前
        2
  •  1
  •   Rowland Shaw    16 年前

        3
  •  1
  •   Adam Robinson    16 年前

    SqlCommand dr.Read()

    SqlCommand insertCommand = new SqlCommand(connection);
    
    insertCommand.CommandText = @"
    insert into [all_table_information]
    (table_id, column_name, data_type, max_char_length)
    values
    (@table_id, @column_name, @data_type, @max_char_length)";
    
    ...create your parameters and add them here
    
    insertCommand.Prepare(); //precompiles the query
    while (dr.Read())
    {
        ...set parameter values
    
        insertCommand.ExecuteNonQuery();
    } 
    dr.Close();