读取文件并查找字符串是否存在并返回表名

时间:2018-02-13 22:17:35

标签: ruby ruby-on-rails-3

我正在尝试读取一个文件,如果该文件有' alter table'然后它必须搜索'修改'如果存在修改则必须返回表名。为此我写了下面的代码,它的工作原理。

filename='modify_table.sql'
bol1="false"
File.foreach(filename).with_index do |line, line_num|

#convert all characters to upper case
 if ( line =~ /[a-z]/ )
 line = line.upcase
 end
  if (line =~ /ALTER TABLE/) 

    location = line.index("ALTER TABLE") + 11
    subline = line[location..-1]
    sublineParts = subline.split(" ")
    tableName = sublineParts[0]

    bol1 = line.include?("MODIFY")
    if (bol1)
    puts " found modify column on #{tableName}"
  else
    puts " no modify found"
  end
end
end

我的文件包含:

begin
BEGIN EXECUTE IMMEDIATE 'alter table schemaname.tablename 
modify (
abc              VARCHAR2(200 BYTE),
xyz               VARCHAR2(200 BYTE)
)'; EXCEPTION when others then if (SQLCODE != -01430 and SQLCODE != -942) then RAISE; end if; END;
end;
/

如果alter和modify在我的代码工作的同一行。 在上面的文件中,两者都是diff行。所以即使文件中有修改,我写的代码也不会返回修改。 有人可以帮助我如何阅读下一行并找到修改

1 个答案:

答案 0 :(得分:0)

这不是解决问题的最佳方法。但是这段代码会让它运转起来。

filename='modify_table.sql'
bol1 = false
lookformodify = false
tableName = ''
File.foreach(filename).with_index do |line, line_num|
  # convert all characters to upper case
  line = line.upcase if line =~ /[a-z]/
  if !lookformodify && line =~ /ALTER TABLE/
    lookformodify = true

    location = line.index('ALTER TABLE') + 11
    subline = line[location..-1]
    sublineParts = subline.split(' ')
    tableName = sublineParts[0]

    bol1 = line.include?('MODIFY')
    if bol1
      puts " found modify column on #{tableName}"
      lookformodify = false # found on same line. No need to look on other lines
    end
  elsif lookformodify && line =~ /MODIFY/
    puts " found modify column on #{tableName}"
    lookformodify = false # found on different line. No need to look on other lines
  end
end