I am using ruby on rails with postgresql. I have a table called "teams" with column "team_name". This "team_name" contains values like "1(Team1)", "1(Team2)", "2(Team1)", etc. Now want to take Team1, Team2, Team3 from those team names using sql query. If I use split_part as follows
sql = "SELECT SPLIT_PART(team_name,'(',2) FROM teams where id=20"
result = ActiveRecord::Base.connection.execute(sql).to_a
In the result I am getting
[{"split_part"=>"Team1)"}]
but I want the following result
[{"split_part"=>"Team1"}]
You can use SUBSTRING, but special characters must be escaped (backslash in this case):
Team
.select("SUBSTRING(team_name FROM '(Team\\d+)') AS team_name")
.where(id: id)
Related
I have that method:
public User FindBySector(string userId)
{
var cn = _context.Database.Connection;
var sql = #"SELECT Sector FROM AspNetUsers nu where nu.Id = :userId";
return DbContext.Database.Connection.Query<User>(sql, new { userId }).FirstOrDefault();
}
I was using sql server, but I will have to switch to oracle.
When performing this search the return is that the table does not exist.
If I search using sql developer it returns what I need, but there I have to put double quotes in the table name and fields, but using dapper it doesn't accept.
Thats the query that work using sql developer
SELECT "Sector" FROM "AspNetUsers" where "AspNetUsers"."Id" = 'fab00ef6-cc2d-4021-9562-ff61bff9cdab';
How do I replace these double quotes inside the dapper code?
If you ported your sqlserver to oracle and when doing so you wrapped your table names in " " then you kinda let yourself in for a world of pain, because all your table names are now case sensitive in Oracle and you have to supply the " ";
SELECT * FROM "AspNetUsers" --returns rows
SELECT * FROM AspNetUsers --becomes ASPNETUSERS and there is no such table
You can sort this out(make your life easier) though by renaming them and leaving out the quotes on the to:
RENAME "AspNetUsers" TO AspNetUsers
Oracle will convert the name to uppercase and will now work in queries no matter what case you specify (omit " ). This will work fine after you rename:
SELECT * FROM asPnEtUSerS
This will work:
SELECT * FROM "ASPNETUSERS"
This won't work:
SELECT * FROM "asPnEtUSerS"
If you have hundreds of tables and columns to rename I suggest you write a program that reads from USER_TAB_COLUMNS to list all your columns and programmatically issue renames for all of them. You could also write an sql that writes an sql, perhaps like:
SELECT
'RENAME COLUMN "'||table_name||'"."'||column_name||'" TO '||column_name
FROM user_tab_columns
Copy the results of this sql out of the results grid and paste it in again as a query and run it. You might need to add semicolons or something to separate them
I have on array like below,
skills = ['ruby','Ruby on Rails'];
I am trying to pass array in mysql where condition like below
questions = MysqlConnection.connection.select_all("
SELECT questions.*,quest_answers.* FROM `questions`
INNER JOIN `quest_answers` ON `quest_answers`.`question_id` =
`questions`.`id` where questions.category IN (#{skills.join(', ')})")
But it did not work,How can pass an array to where In condition.
Error I am getting
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'on rails, Ruby)' at line 1: SELECT questions.*,quest_answers.* FROM `questions` INNER JOIN `quest_answers` ON `quest_answers`.`question_id` = `questions`.`id` where questions.category IN (Ruby on rails, Ruby)
You are passing a string representation of the array to MySQL, which doesn't work. You need to insert the values in the array into the query. This can be done by escaping the skills, and joining them:
skills.map { |s| "'#{s}'" }.join(', ')
This produces 'ruby', 'Ruby on Rails', which is a valid argument for the IN statement.
A better approach however is to not write the raw SQL at all, but rely on ActiveRecord to generate it. This is the more maintainable and readable approach.
Question.joins(:quest_answers).where(category: skills)
Passing an array to where converts it automatically into a subset condition.
I am using sqlite in one my ios project where among other columns there are two columns. one has country code for mobile dialing like +880 and other column has rest of the mobile number like 1912353697. Now i want to join values from these two columns and compare the result value against like +8801912353697 and if matches pull the corresponding name value in that table . what would be the right query. I have tried like SELECT name FROM CONTACT_LIST WHERE (SELECT mblDc || mbl FROM CONTACT_LIST) = "+8801617634317" ; but that does not work .
A help would be appreciated.
Try:
SELECT name FROM CONTACT_LIST
WHERE mblDc || mbl = "+8801617634317";
From SQLite documentation: The || operator is "concatenate" - it joins together the two strings of its operands.
please check
How to concatenate strings with padding in sqlite
using substr function we can do the job and the query should be like
SELECT name FROM CONTACT_LIST WHERE (mblDc || mbl) = "+8801617634317" ;
How can I order query results by an hstore attribute?
#items = Item.includes(:product).order('products.properties #> hstore("platform")')
Causes
PG::Error: ERROR: column "platform" does not exist
LINE 1: ...oduct_id" ORDER BY products.properties #> hstore("platform"...
platform is a hstore key, stored in the properties column, which is an hstore type.
Double quotes are used to quote identifiers (such as table and column names) in PostgreSQL (and other databases that follow the standard). So when you say:
hstore("platform")
PostgreSQL sees "platform" as a quoted column name and since there is no platform column, you get an error.
Strings in standard SQL are quoted with single quotes, you want to say:
.order("products.properties #> hstore('platform')")
This will probably still fail though, hstore('platform') doesn't make much sense and neither does using #> here; a #> b means
does the hstore a contain the hstore b
If you're trying to sort on the value of the 'platform' key in the properties hstore then you'd want to use -> to lookup the 'platform' key like this:
.order("products.properties -> 'platform'")
I'm using Rails to get data from Postgresql by passing dynamic column and table name.
I cannot use ActiveRecord because the shape data that is imported from shapefile is dynamic both table and column name.
I have to use double quote with a column name in the query to avoid problem such column name: "addr:city" for example.
def find_by_column_and_table(column_name, shape_table_name)
sql = "SELECT \"#{column_name}\" FROM \"#{shape_table_name}\" WHERE \"#{column_name}\" IS NOT NULL"
ActiveRecord::Base.connection.select_one(sql)
end
2 examples of generated sql statement:
SELECT "place" FROM "shp_6c998258-32a6-11e0-b34b-080027997e00"
SELECT "addr:province" FROM "shp_6c998258-32a6-11e0-b34b-080027997e00"
I want to make sure there is no sql injection in the query.
Could anyone point me how to solve this issue?
The recommended way to prevent injection, speed up your query and catch errors is to use positional parameters or stored proceedures. Anything less is asking for trouble.
http://nasir.wordpress.com/2007/12/03/stored-procedures-and-rails/
http://www.postgresql.org/docs/9.0/static/sql-expressions.html#AEN1834