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:

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


   1  
   2  class Array
   3    def add_condition(condition, conjunction='and')
   4      if condition.is_a? Array
   5        if self.empty?
   6          (self << condition).flatten!
   7        else
   8          self[0] += " #{conjunction} " + condition.shift
   9          (self << condition).flatten!
  10        end
  11      elsif condition.is_a? String
  12        self[0] += " #{conjunction} " + condition
  13      else
  14        raise "don't know how to handle this condition type"
  15      end
  16      self
  17    end
  18  end

SQLListColumn

a string/text column with comma-separated values

   1  
   2  class SQLListColumn < String
   3    SEPARATOR = ','
   4    def contains(value)
   5      "#{self} like '%#{SEPARATOR}#{value}#{SEPARATOR}%' or #{self} like '#{value}#{SEPARATOR}%' or #{self} like '%#{SEPARATOR}#{value}' or #{self} = '#{value}'"
   6    end
   7  end


Usage:

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


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

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


Rails usage might look like this:

   1  
   2  Program.find(
   3    :all,
   4    :conditions => \
   5      SQLListColumn.new('admins').contains(username) \
   6      + ' or ' + \
   7      SQLListColumn.new('viewers').contains(username),
   8    :order => 'name'
   9  )

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...

   1  
   2  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...

   1  
   2  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.

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