Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Tim Morgan http://timmorgan.org

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

Rails Array#add_condition Method

Lets you add a condition to a set of ActiveRecord conditions easily like this:

  conditions = ['active = ? and type = ?', true, 2]
  conditions.add_condition ['person_id = ?', 345]


class Array
  def add_condition(condition, conjunction='and')
    if condition.is_a? Array
      if self.empty?
        (self << condition).flatten!
      else
        self[0] += " #{conjunction} " + condition.shift
        (self << condition).flatten!
      end
    elsif condition.is_a? String
      self[0] += " #{conjunction} " + condition
    else
      raise "don't know how to handle this condition type"
    end
    self
  end
end

SQLListColumn

a string/text column with comma-separated values

class SQLListColumn < String
  SEPARATOR = ','
  def contains(value)
    "#{self} like '%#{SEPARATOR}#{value}#{SEPARATOR}%' or #{self} like '#{value}#{SEPARATOR}%' or #{self} like '%#{SEPARATOR}#{value}' or #{self} = '#{value}'"
  end
end


Usage:

SQLListColumn.new('admins').contains('tmorgan')


...gives you a string you can use in a SQL query:

"admins like '%,tmorgan,%' or admins like 'tmorgan,%' or admins like '%,tmorgan' or admins = 'tmorgan'"


Rails usage might look like this:

Program.find(
  :all,
  :conditions => \
    SQLListColumn.new('admins').contains(username) \
    + ' or ' + \
    SQLListColumn.new('viewers').contains(username),
  :order => 'name'
)

Find a table column on SQL Server

I often find myself looking for a specific database column that I have no idea where to find. Pouring over hundreds of tables is painful. One way to quickly narrow the search is to use this query...

SELECT name FROM sysobjects WHERE id IN ( SELECT id FROM syscolumns WHERE name = 'THE_COLUMN_NAME' )


...or, if you're unsure exactly what the column is named, but you suspect you know part of the name, then try...

SELECT name FROM sysobjects WHERE id IN ( SELECT id FROM syscolumns WHERE name like '%PART_OF_NAME%' )

copy table from one database to another in MsSQL

This works in Microsoft SQL Server; don't know about other databases.

SELECT * INTO NewTable FROM existingdb.dbo.existingtable;
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS