Building SQL queries with Ruby
Now that I can require "dbi" in my scripts and have access to ODBC databases, I worked out what I think is an easy way of building dynamic SQL strings from an array of field names. Consider the following:
search = 'findme'
fields = ['ServiceClientID', 'Company', 'Firstname', 'Lastname', 'HomePhone',
'WorkPhone', 'MobilePhone', 'MailingAddress', 'Email', 'SiteAddress',
'SiteContact', 'Region']
sql = "SELECT " + fields.join(', ') + "
FROM tblServiceClients
WHERE " + fields.map {|f| like_search(f, search)}.join(' OR ') + "
ORDER BY Firstname, Lastname"
This requires a method called like_search which takes two parameters: the field name and the search string. It looks like this:
def like_search(f, search)
"#{f} LIKE '%#{search}%'"
end
Altering the fields means that you add or remove elements in the fields array. Although it's not anywhere near as nice as the interfaces that Rails provides, it's still very handy. The resulting SQL string is:
SELECT ServiceClientID, Company, Firstname, Lastname, HomePhone,
WorkPhone, MobilePhone, MailingAddress, Email, SiteAddress,
SiteContact, Region
FROM tblServiceClients
WHERE ServiceClientID LIKE '%find_me%' OR Company LIKE '%find_me%'
OR Firstname LIKE '%find_me%' OR Lastname LIKE '%find_me%'
OR HomePhone LIKE '%find_me%' OR WorkPhone LIKE '%find_me%'
OR MobilePhone LIKE '%find_me%' OR MailingAddress LIKE '%find_me%'
OR Email LIKE '%find_me%' OR SiteAddress LIKE '%find_me%'
OR SiteContact LIKE '%find_me%' OR Region LIKE '%find_me%'
ORDER BY Firstname, Lastname