Duplicate quotes in a postgres string - sql

I have a function that generates a new user in the database.
I would like to check if the email address contains any quotes and if it does, I would like to duplicate them.
For example, I have the following email address: test.o'test#test.com and I would like to transform it into test.o''test#test.com.
Could anybody help me with this?
Thank you

Assuming you expect only one single quote (and not double or more), you could try using a simple replace:
UPDATE yourTable
SET email = REPLACE(email, '''', '''''');

Related

Wildcard, '%', within ColdFusion cfscript query LIKE statement?

Is it possible to use a wildcard in a SQL LIKE statement within a ColdFusion cfscript query?
An example that doesn't work:
local.q = new Query();
local.q.setDatasource(variables.dsn);
local.q.addParam(name='lastname', value='%' & arguments.lastname, cfsqltype="cf_sql_varchar");
local.qString = 'SELECT name FROM users WHERE lastname LIKE :lastname';
local.q.setSQL(local.qString);
local.result = local.q.execute().getResult();
I also tried these, which didn't work:
local.qString = 'SELECT name FROM users WHERE lastname LIKE %:lastname';
local.qString = "SELECT name FROM users WHERE lastname LIKE '%:lastname'";
UPDATE:
I am using MS SQL Server 2008.
The query works fine within SQL Server Mgmt Studio... I think it has something to do with how to format the query within cfscript tags?
Yes, it is possible. You're setting it in the param, which is correct. I'm not sure why it's not working with you.
I did the following and it worked.
var qryArgsCol = {};
qryArgsCol.datasource = variables.datasource;
qryArgsCol.SQL = "
SELECT ID
FROM Users
WHERE LastName LIKE :searchStringParam
";
var qryGetID = new query(argumentCollection=qryArgsCol);
qryGetID.addParam(name="searchStringParam", value="%" & searchString, cfsqltype="cf_sql_varchar");
qryGetIDResult = qryGetID.execute().getResult();
There's a response here from Adam Cameron, which was apparently deleted by an overzealous mod.
Rather than repeat what he says, I've just copied and pasted (with emphasis added to the key parts):
Just to clarify that the syntax you tried in your first example does work. That is the correct approach here. To clarify / explain:
The <cfquery> version of the example you have would be along the lines of:
<cfqueryparam value="%foo">
So in the function version, the param would be ? or :paramName and the value of the param would continue to be "%foo".
The % is part of the param value, not the SQL string.
So given that "doesn't work" for you, it would help if you posted the error, or whatever it is that causes you to think it's not working (what your expectation is, and what the actual results are). Then we can deal with the actual cause of your problem, which is not what you think it is, I think.
Does the query work fine as a <cfquery>?
Depending on the dbms used, that single and double quotes may be interpreted when the sql statement is run. What dbms are you using? Your statement now doesn't select for the value in the variable, but for any user whose lastname is "lastname". It should be something like:
lastname like '%#lastname#'
Just remember that you ultimately need to see what CF gives the DB server. In this instance, you can try this mockup to get close and find the same error in SSMS by messing with the quotes/value in the param declaration:
declare #param1 varchar(max) = '%Eisenlohr';
SELECT name FROM users WHERE lastname LIKE #param1
I just ran into the same problem as the original poster where it "wasn't working" and I didn't get any results from the query of queries.
The problem for me is that the wildcard search is case-sensitive.
local.q = new Query();
local.q.setDatasource(variables.dsn);
local.q.addParam(name='lastname', value='%' & LCase(arguments.lastname), cfsqltype="cf_sql_varchar");
local.qString = 'SELECT name FROM users WHERE LOWER(lastname) LIKE :lastname';
local.q.setSQL(local.qString);
local.result = local.q.execute().getResult();
So what I did was made sure the incoming argument was lower case and made sure the comparing field in the SQL was lower case as well and it worked.
Use like this.
local.q = new Query();
local.q.setDatasource(variables.dsn);
local.q.addParam(name="lastname", cfsqltype="cf_sql_varchar",value='%ARGUMENTS.lastname' );
local.qString = 'SELECT name FROM users WHERE lastname LIKE :lastname';
local.q.setSQL(local.qString);
local.result = local.q.execute().getResult();
I would suggest using the CFQuery tag instead of attempting to run queries within CFScript. Unless you REALLY know what you are doing. I say this because the CFQuery tag has some built-in functionality that not only makes building queries easier for you but may also protect you from unforeseen attacks (the SQL injection type). For example, when using CFQuery it will automatically escape single-quotes for you so that inserting things like 'well isn't that a mess' will not blow up on you. You also have the benefit of being able to use the CFQueryParam tag to further battle against SQL injection attacks. While you may be able to use the CFQueryParam functionality within CFScript it is not as straight forward (at least not for me).
See this blog post from Ben Nadel talking about some of this.
So in CFQuery tags your query would look something like this:
<cfquery name="myQuery" datasource="#variables.dsn#">
SELECT name
FROM users
WHERE lastname LIKE <cfqueryparam cfsqltype="cf_sql_varchar" value="%:#arguments.lastname#" maxlength="256" />
</cfquery>

Replace space with dash before save using Rails 3

I am trying to save a name to the database and a single word (firstname) works fine but when the user enter both firstname and lastname I want Rails to save it to the database as firstname-lastname instead of firstname lastname (space between).
I know I perhaps should use a before create filter but I am not sure how this need to look like. I want the validation to work to, i.e. no two people should be able to use the same name.
I am using Rails 3.
You can use ActiveSupport's inflector method parameterize on the string.
name = 'john smith' # => john smith
name.parameterize # => john-smith
Further, parameterize takes an option to use for the word-break, so you can replace the dash with an underscore like this:
name.parameterize("_") # => john_smith
An advantage of using parameterize is that it normalizes the characters to the latin, so...
name = "jöhanne såltveç"
name.parameterize # => johanne-saltvec
EDIT: As of Rails 5.0.0.1 the separator needs to be passed as an option. Therefore: name.parameterize(separator: '_')
Why don't you just have first_name and last_name columns in the db, and create your own validation rule to make sure the combination is unique (http://guides.rubyonrails.org/active_record_validations_callbacks.html#creating-custom-validation-methods). You should also create a unique index over those two columns in your db.
Another option would be to us regexp and replace all existing spaces with. You'd put something along the lines of:
self.firstname.gsub(/\s+/, '-')
in your model.
Note: I'm not sure if ruby accepts \s as "any whitespace character" And I think the * should make sure that if someone enters a name with two neighbour spaces(or more) it won't convert each space into a separate dash, but only into one.
Other answer is correct,
But, if you want to preserve case while parameterizing
name = "Donald Duck"
name.parameterize(preserve_case: true) # => Donald-Duck

SQL Server 2005 - Incorrect syntax near '/'

Here's a very easy question for someone :)
Trying to update an SQL column with the following:
UPDATE [NameOfTable]
SET [HtmlContent] = 'a href="/sell-your-boat/"'
WHERE HtmlID = 123456
But am getting the following error message: Incorrect syntax near '/'.
I know it's because I need to escape the / character but hitting my head against the wall trying to find the answer because I am aware it's probably very simple!
Thank you
You don't need to escape slashes in a string in SQL. The only chracter that you need to escape is apostrophe (').
There is nothing wrong with the query that you are showing, so the only explanation is that the code that you are actually running does not look like that.
It doesn't make sense to have HTML-encoded quotation marks around a href attribute, so my guess is that the HTML code actually looks something like this:
<a href='/sell-your-boat/'>
Any apostrophes in the text would have to be encoded as double apostrophes when you put it in a string literal in the SQL code.
I don't know where the query is executed from, but a parameterised query would be preferrable if possible, as then you don't have to escape the text yourself, you just assign the text to the property value.
Like all the comments above, youd don't need to escape the /
I just did a quick sql test in sql server 2005 and didn't get an error message (see below)
We'll probably need more information than what you provided. Are you running this in Management studio, or is this sql being called in a .NET application, etc...
create table test (htmlid int, htmlcontent varchar(516))
insert into test select 123456 as htmlid, 'test' as htmlcontent
update test
set htmlcontent = 'a href="/sell-your-boat/"'
where htmlid = 123456
select * from test where htmlid = 123456
drop table test
my output
123456 a href="/sell-your-boat/"

SQL: Find and Replace with SQL?

I have a MySQL InnoDB database.
I have a column my in 'article' table called url that needs to be updated.
Stored in article.url =
/blog/2010/article-name
/blog/1998/the-article-name
/blog/...
I need to change /blog/ to /news/. (E.g. now article.url = '/news/...')
What is the SQL needed to replace "/blog/" with "/news/" in the article.url column?
update url
set article = replace(article, '/blog/', '/news/')
where article like '/blog/%'
If every url starts with "/blog/" and you don't want to change anything except the prefix, then you can just use substring() and concat() instead of replace():
update article
set url = concat('/news/',substring(url,7))
where url like '/blog/%';
I recently wanted to replace a string within MySQL on the fly, but the field could contain 2 items. So I wrapped a REPLACE() within a REPLACE(), such as:
REPLACE(REPLACE(field_name, “what we are looking for”, “replace first instance”),
“something else we are looking for”, “replace second instance”)
This is the syntax I used to detect a boolean value:
REPLACE(REPLACE(field, 1, “Yes”), 0, “No”)
Hope this helps!

regular expression to pull words beginning with #

Trying to parse an SQL string and pull out the parameters.
Ex: "select * from table where [Year] between #Yr1 and #Yr2"
I want to pull out "#Yr1" and "#Yr2"
I have tried many patterns, but none has worked, such as:
matches = Regex.Matches(sSQL, "\b#\w*\b")
and
matches = Regex.Matches(sSQL, "\b\#\w*\b")
Any help?
You're trying to put a word boundary after the #, rather than before. Maybe this:
\w(#[A-Z0-9a-z]+)
or
\w(#[^\s]+)
I would have gone with
/^|\s(#\w+)\s|$/
or if you didn't want to include the #
/^|\s#(\w+)\s|$/
though I also like joel's above, so maybe one of these
/^|\s(#[^\s]+)\s|$/
/^|\s#([^\s]+)\s|$/