How to escape quotes in strings in vertica (vsql)? - database

So I need to insert some values into a vertica database (via vsql), which may contain quotes and all sorts of special characters. But vertica does not seem to understand character escaping. For example:
rpt=> select "asdasda\"asdasdad" from some_table limit 1;
rpt"> ";
ERROR: syntax error at or near "" from some_table limit 1;
"" at character 26
LINE 1: select "asdasda\"asdasdad" from some_table limit 1;
This is not the insert statement, but you should get the idea.

Well, first off I should have used single quotes. Escape sequences used to work in earlier versions (before 4.0 I believe), but now they are off by default. If you do not want to tweak database config parameters you have two options.
Use E' syntax:
select E'somethin\' here' from v_catalog.dual_p;
Or double the quotes that need to be escaped:
select 'somethin'' here' from v_catalog.dual_p;

Related

Using like to query 100% key word in SQL Server

I am trying to query Keyword 100% using Like command.
LIKE (‘%100%%’)
But the command is querying for all keywords with 100 which is not what I
want
Use Escape Character.
Try:
Select * from MyTable m where m.Column1 like '%100\%%' escape '\'
Escape Character can be set as per your convenience.
In the above query, replace MyTable with your table name and Column1 with your Column Name.
You could also take advantage of SQL Server's LIKE operator's regex syntax, and use [%] to represent a literal percent:
SELECT *
FROM yourTable
WHERE col LIKE '%100[%]%';
Demo
I prefer this method to the accepted answer because it makes more explicit the intention to represent a literal character, and it avoids the possible need for an ESCAPE clause.

alternative to single quote in MSSQL query

My question may be silly.
I have an application that does not like single quotes.
I want to execute SQL query from that application.
When I form my SQL query, I cannot use single quotes.
I am looking for alternative way for single quotes.
I am on MicroSoft SQL 2012.
Example, my SQL is like this,
SELECT name
FROM People
WHERE peopleId = '123'
However I want to write this without single quotes,
Something like below I was trying,
SELECT name
FROM People
WHERE peopleId = CHAR(39)123CHAR(39)
Thank you
If it accepts double quotes...
SET QUOTED_IDENTIFIER ON
GO
https://msdn.microsoft.com/en-us/library/ms174393.aspx
When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double quotation marks, and literals must be delimited by single quotation marks. When SET QUOTED_IDENTIFIER is OFF, identifiers cannot be quoted and must follow all Transact-SQL rules for identifiers. For more information, see Database Identifiers. Literals can be delimited by either single or double quotation marks.
If your PeopleID or filter value is initially a numeric value you can do this. If it is not numeric I don't know.
SELECT name
FROM People
WHERE peopleId = CAST(123 AS VARCHAR(25))

How to replace semicolons?

I have an SQL SELECT query that's grabbing some data from my database. I need to replace a certain word that contains a semicolon in my SELECT query. Exactly this:
REPLACE(Table.Field,'"','') AS Field1
The error I'm getting reads
Unclosed quotation mark after the character string '"'.
So I think the semicolon is terminating the query. How can I escape that semicolon?
I tried backslashes and using double quotes.
Some sample data and expected output, as requested
Sample data
Field
"Hello"
"Goodbye"
Expected output
Field1
Hello
Goodbye
Full Query
SELECT REPLACE(Table.Name,';','') AS Name,
SUM(Table.Quantity) AS Quantity,
SUM(Table.Price*Table.Quantity) AS Price
FROM Table
GROUP BY Name
The ; symbol doesn't terminate the query and it should not be escaped, if it is part of the string literal (the text enclosed in single quotes ').
Here is a complete example that demonstrates that it works fine in SSMS:
CREATE TABLE #TempTable (Name varchar(50));
INSERT INTO #TempTable (Name) VALUES('Field');
INSERT INTO #TempTable (Name) VALUES('"Hello"');
INSERT INTO #TempTable (Name) VALUES('"Goodbye"');
SELECT
Name
,REPLACE(Name,'"','') AS ReplacedName
FROM #TempTable;
DROP TABLE #TempTable;
This is the result set:
Name ReplacedName
---- ------------
Field Field
"Hello" Hello
"Goodbye" Goodbye
You didn't provide all details of how you construct and execute your query, so I have a guess. It looks like you are:
building the text of the query dynamically
use some web-based tools/languages/technologies for that
web-based text processing tool/language that you use parses the text of your SQL query as if it was HTML and interferes with the result. For one thing, it changes " to the " symbol.
during all this processing you end up with unmatched ' symbol in the text of your SQL. It could come from the user input that you concatenate to your query of from a value stored in your database.
it has nothing to do with the ; symbol. Your error message clearly states that the matching quotation mark (which is ') is missing after the " symbol.
To understand what is going on you should print out the text of the actual SQL query that is sent to the server. Once you have it, it should become obvious what went wrong. I don't think that the Full Query that you put in the question is the real query that you are trying to run. It has syntax error. So, get the real thing first.
This works fine for me
declare #a as nvarchar(50) = '"Hello"'
select REPLACE(#a,'"','') AS Field1
declare #b as nvarchar(50) = '"Goodbye"'
select REPLACE(#b,'"','') AS Field1
Error message says unclosed quotation mark ?
Do you have single quotes in few of your fields ?
In that case you can replace them first as below
REPLACE(Table.Field,'''','') AS Field1
Let me know you need more help with this.
Source
"
the double quote sign "
I think there is no where that this parameter is known as a special phrase that refers to " and cause you error message.
In SQL Server there is just a function like QUOTENAME ( 'character_string' [ , 'quote_character' ] ) that used like this: -Just for ' or " or []-
SELECT QUOTENAME('Sample', '"') --> result is `"Sample"`
SELECT QUOTENAME('Sam"ple', '"') --> result is `"Sam""ple"`
In SQL Server identifiers can be delimited by ", When SET QUOTED_IDENTIFIER is ON -for following the ISO rules-. When SET QUOTED_IDENTIFIER is OFF, identifiers cannot be quoted and must follow all Transact-SQL rules for identifiers. Literals can be delimited by either single or double quotation marks.
I suggest you using SET QUOTED_IDENTIFIER OFF that make sure, that you've not identifier between " in your query.
Note:
When a table is created, the QUOTED IDENTIFIER option is always stored as ON in the table's metadata even if the option is set to OFF when the table is created.
If you are using a SQL string I suggest this syntax:
REPLACE(Table.Field, CHAR(34), '') As Field1
or
REPLACE(REPLACE(Table.Field, ';', '.'), '&quot.', '') As Field1

Escape Character in SQL Server

I want to use quotation with escape character. How can I do to avoid the following error when one has a special character?
Unclosed quotation mark after the character string.
You can escape quotation like this:
select 'it''s escaped'
result will be
it's escaped
To escape ' you simly need to put another before: ''
As the second answer shows it's possible to escape single quote like this:
select 'it''s escaped'
result will be
it's escaped
If you're concatenating SQL into a VARCHAR to execute (i.e. dynamic SQL), then I'd recommend parameterising the SQL. This has the benefit of helping guard against SQL injection plus means you don't have to worry about escaping quotes like this (which you do by doubling up the quotes).
e.g. instead of doing
DECLARE #SQL NVARCHAR(1000)
SET #SQL = 'SELECT * FROM MyTable WHERE Field1 = ''AAA'''
EXECUTE(#SQL)
try this:
DECLARE #SQL NVARCHAR(1000)
SET #SQL = 'SELECT * FROM MyTable WHERE Field1 = #Field1'
EXECUTE sp_executesql #SQL, N'#Field1 VARCHAR(10)', 'AAA'
You can define your escape character, but you can only use it with a LIKE clause.
Example:
SELECT columns FROM table
WHERE column LIKE '%\%%' ESCAPE '\'
Here it will search for % in whole string and this is how one can use ESCAPE identifier in SQL Server.
You need to just replace ' with '' inside your string
SELECT colA, colB, colC
FROM tableD
WHERE colA = 'John''s Mobile'
You can also use REPLACE(#name, '''', '''''') if generating the SQL dynamically
If you want to escape inside a like statement then you need to use the ESCAPE syntax
It's also worth mentioning that you're leaving yourself open to SQL injection attacks if you don't consider it. More info at Google or: http://it.toolbox.com/wiki/index.php/How_do_I_escape_single_quotes_in_SQL_queries%3F
Escaping quotes in MSSQL is done by a double quote, so a '' or a "" will produce one escaped ' and ", respectively.
If you want to escape user input in a variable you can do like below within SQL
Set #userinput = replace(#userinput,'''','''''')
The #userinput will be now escaped with an extra single quote for every occurance of a quote
WHERE username LIKE '%[_]d'; -- #Lasse solution
WHERE username LIKE '%$_d' ESCAPE '$';
WHERE username LIKE '%^_d' ESCAPE '^';
FROM:
SQL Server Escape an Underscore
You could use the **\** character before the value you want to escape e.g
insert into msglog(recipient) values('Mr. O\'riely')
select * from msglog where recipient = 'Mr. O\'riely'
To keep the code easy to read, you can use square brackets [] to quote the string containing ' or vice versa .

Replace single quotes in SQL Server

I have this function in SQL Server to replace single quotes.
But when I insert a single quote it throws an error on Replace(#strip,''','')):
Create Function [dbo].[fn_stripsingleQuote]
(#strStrip varchar(Max))
returns varchar
as
begin
declare #CleanString varchar(Max)
SET #var=(Replace(#strip,'',''))
return #var
end
You need to double up your single quotes as follows:
REPLACE(#strip, '''', '')
Try REPLACE(#strip,'''','')
SQL uses two quotes to represent one in a string.
If you really must completely strip out the single quotes you can do this:
Replace(#strip, '''', '')
However, ordinarily you'd replace ' with '' and this will make SQL Server happy when querying the database. The trick with any of the built-in SQL functions (like replace) is that they too require you to double up your single quotes.
So to replace ' with '' in code you'd do this:
Replace(#strip, '''', '''''')
Of course... in some situations you can avoid having to do this entirely if you use parameters when querying the database. Say you're querying the database from a .NET application, then you'd use the SqlParameter class to feed the SqlCommand parameters for the query and all of this single quote business will be taken care of automatically. This is usually the preferred method as SQL parameters will also help prevent SQL injection attacks.
You could use char(39)
insert into my_table values('hi, my name'+char(39)+'s tim.')
Or in this case:
Replace(#strip,char(39),'')
Looks like you're trying to duplicate the QUOTENAME functionality. This built-in function can be used to add delimiters and properly escape delimiters inside strings and recognizes both single ' and double " quotes as delimiters, as well as brackets [ and ].
Try escaping the single quote with a single quote:
Replace(#strip, '''', '')
We have to double the number of quotes.
To replace single quote :
REPLACE(#strip, '''', '')
To replace double quotes :
REPLACE(#strip, '''''', '')
If escaping your single quote with another single quote isn't working for you (like it didn't for one of my recent REPLACE() queries), you can use SET QUOTED_IDENTIFIER OFF before your query, then SET QUOTED_IDENTIFIER ON after.
For example
SET QUOTED_IDENTIFIER OFF;
UPDATE TABLE SET NAME = REPLACE(NAME, "'S", "S");
SET QUOTED_IDENTIFIER OFF;
I ran into a strange anomaly that would apply here. Using Google API and getting the reply in XML format, it was failing to convert to XML data type because of single quotes.
Replace(#Strip ,'''','')
was not working because the single quote was ascii character 146 instead of 39.
So I used:
Replace(#Strip, char(146), '')
which also works for regular single quotes char(39) and any other special character.
Try this :
select replace (colname, char(39)+char(39), '') AS colname FROM .[dbo].[Db Name];
I have achieved the desired result.
Example : Input value --> Like '%Pat') '' OR
Want Output --> *Like '%Pat') OR*
using above query achieved the desired result.
The striping/replacement/scaping of single quotes from user input (input sanitation), has to be done before the SQL statement reaches the database.
Besides needing to escape the quote (by using double quotes), you've also confused the names of variables: You're using #var and #strip, instead of #CleanString and #strStrip...
I think this is the shortest SQL statement for that:
CREATE FUNCTION [dbo].[fn_stripsingleQuote] (#strStrip varchar(Max))
RETURNS varchar(Max)
AS
BEGIN
RETURN (Replace(#strStrip ,'''',''))
END
I hope this helps!
select replace ( colname, '''', '') AS colname FROM .[dbo].[Db Name]

Resources