Escaping an apostrophe in Sqldf with R - sql

I have a dataframe mergeTest which have a column Name with apostrophes on few values,
So I'm looping through it to divide values which denominator are contained in the table nbrToDivide
test1 <- sqldf(c(paste('UPDATE mergeTest SET Value = Value/',nbrToDivide[i],
' WHERE `Year` =',nbrToDivide$`Year`[i],
' AND UPPER(Name) = \'',nbrToDivide$Name[i],sep=""),
'SELECT * from mergeTestt'))
The problem is when the value of UPPER(Name) contains an apostrophe in it, it will interprete it and return an error.
I tried to use gsub with grepl but it adds two backslashes to my names so I dunno if there is a way to deal with it or should I just suppress the apostrophe in my two datraframes ?

Double the single quote. Here is an example:
> sqldf("select 'O''Brian' Name")
Name
1 O'Brian

Replacing one single quote with two single quotes will fix this as in :
"SELECT * FROM TableName WHERE FieldName = 'QueryString''s Value'"

Related

Unable to pass variable in Informix

I was able to figure out how to get connected to Avaya CMS through Informix using SQL. The below query works but when I try to replace the ''1/01/19'' with a variable, I get the following error: "EIX000: (-1205) Invalid month in date"
Code that works
select * from Openquery(CMS, 'select * FROM dagent WHERE ROW_DATE = ''1/01/19'' ');
Code that does not work
DECLARE #startDate DATETIME
SET #startDate = '2021-01-21'
select * from Openquery(CMS, 'select * FROM dagent WHERE ROW_DATE = ''+#startDate+'' ');
Does anyone have an idea what the problem could be?
The trouble is not enough single quotes.
You have:
'select * FROM dagent WHERE ROW_DATE = ''+#startDate+'' '
^^ ^^
In each case where you have two adjacent single quotes, you need a third too. The two single quotes map to one single quote, so the quoted string contains +#startDate+, not the concatenation of your variable.
You need:
'select * FROM dagent WHERE ROW_DATE = '''+#startDate+''' '
Now the first two single quotes in the triplet map to a single quote; the third terminates the string, the +#startDate+ becomes string concatenation, and then the next single quote starts a new string, the two single quotes map to one quote, and the space and single quote finish the string.
How to debug?
Assign the string you used to a variable and print it.
Assign the string I suggest to a variable and print it.

How to handle/use special characters like percent (%) and ampersand (&) in Oracle SQL queries

I need to include the special character "%" in my LIKE clause in a SQL query, e.g.:
Select * From Some_Table Where Field_Name Like 'bla%bla&2';
How do I write that?
If you want to match Field_Name values that contain 'bla%bla&2', then you need to write this:
set define off
Select * From Some_Table Where Field_Name Like '%bla\%bla&2%' escape '\';
You get to specify which character you want to use to escape a following character (thanks should go to mathguy, not me). You also have to set define off to prevent sqlplus from trying to substitute values in a string.
If, however, you want to match Field_Name values that exactly equal the given string, then you do this instead:
set define off
Select * From Some_Table Where Field_Name = 'bla%bla&2';
If I am not mistakend you escape them with a backslash (\)
Select * From Some_Table Where Field_Name Like 'bla\%bla&2' ESCAPE '\';
Use escape \ to treat is a literal
SELECT *
FROM Some_Table
WHERE Field_Name LIKE 'blah\%'|| 'blah' ||'&'|| '2';
I'll guess that you're using a tool which treats &n, where n is a digit, as a variable marker. If you're using SQL*Plus or SQL Developer you'd need to issue the SQL*Plus command SET DEFINE OFF. Other tools may use other methods to accomplish this.
Best of luck.
I do not think the backslash escape character will work here for the ampersand. Instead, you will want to divide your search into concatenated strings using double pipes. Use single quotes around each piece of literal text. Next, replace the & with chr(38) which is the ampersand. You can see this with:
select chr(38) from dual
You will still want to include the backslash before the % and finish your statement with escape '\'. Notice, I did not quote the chr(38).
select * From Some_Table Where Field_Name Like 'bla\%bla'||chr(38)||'bla' escape '\'

how to SELECT a column which has a space in between its name

I am trying to execute a SQL query through OCCI calls in my CPP program.
I want to read 2 columns out of those one column name has a space in between. I tried enclosing the column name between ' ', " ", [ ] and nothing helped. Can experts suggest me on answering this.
Below is my code:
....
string sqlStmt = "SELECT 'REJECTED COST', APPROVED_COST FROM COST_TABLE where PART_NUM= 'PN4879-1'";
stmt = conn->createStatement(sqlStmt);
ResultSet *rset = stmt->executeQuery();
double dRejCost = 0;
double dAppCost = 0;
if(rset->next())
{
dRejCost = rset->getNumber(1);
dAppCost = rset->getNumber(2);
}
stmt->closeResultSet(rset);
conn->terminateStatement(stmt);
Error/Exception:
The error I get # dRejCost = rset->getNumber(1);:
ORA-01722: invalid number
PS: The ORACLE table has the many columns where "REJECTED COST" column header is named with a space. I don't have the privilege to ask the DB team to change the DB table name though.
Thanks in advance.
Single quotes (') denote character literals. I.e., you're selecting the string 'REJECTED COST', which, obviously, cannot be cast to a number.
In order to select a column name with a space, you should use double quotes ("). Note that they need to be escaped, as you're using them inside a c++ string, which is also denoted by double quotes:
string sqlStmt = "SELECT \"REJECTED COST\", APPROVED_COST FROM COST_TABLE where PART_NUM= 'PN4879-1'";

Matching a String having '%' as a character

I want to match a String using Like operator. The challenge is having '%' as a character in my string.
i.e. Row1 : Column = CT%CNV!XYZABCD...
Row2 : Column = CTXXXCNV!XYZABCDE...
If I use "SELECT * FROM table WHERE Column like 'CT%CNV!%'. It doesn't consider '%' as a character and the statement returns both rows.
I need to return the first row only.
You shoud use escape keyword:
select *
from MyTable
where Column like 'CT\%CNV!XYZABCD%' escape '\'
here '\%' is treated as a plain symbol, while '%' is wild card one
You can use brackets to escape the percent sign :
SELECT * FROM table WHERE Column like 'CT[%]CNV!%'

Replace quote in SQL Select

I have a scenario in my vb.net project where users need to select a name from a combobox (or type a new name).
Names of course can have ' as in Tina O'Hara which in the database would be stored as Tina O''Hara.
My combobox is populated from a sql select command. I have tried to use a Replace so that the names display correctly in the dropdown.
SqlStr = "SELECT Replace(ContactName, '''', ''') AS ddlText FROM tbl_Visits Where CustID = " & hd_CustID.value & " ORDER By ContactName"
PopulateCMBX(cmbx_ContactName, SqlStr, "Please Select")
PopulateCMBX... This gets a list of names from the supplied SqlStr and populates the combobox itemlist with a 'Please Select' as the first option.
SqlStr is producing an error as there is not a matching set of ' how do I fix this. Thanks
When referencing single quotes in MS-SQL, you need to escape each single quote (') with two single quotes ('').
If the name is stored in the database with two single quotes, such as (''), then when you do the replace you need to use four single quotes (''''). In addition to these, you need to enclose the string with single quotes.
What this means is that your replace should look like this:
SqlStr = "SELECT Replace(ContactName, '''''', '''') ...
The 2nd param in the replace has 6 single quotes: 4 to represent the two single quotes you are replacing, and 2 to make it a string. The 3rd param has 4 single quotes: 2 to represent a single escaped quote and two to make it a string.
Try with this, maybe not the best solution but it works (check this example):
select Replace(Replace(ContactName, '''', '$&'),'$&$&','''') from tbl_Visits
Note that $& is like a key that should not affect the values ​​in your field, for example, could be a word: &&k&& or %%key%%, etc.
Back to clarify, it is not the best solution, but sometimes i've used.