How to replace semicolons? - sql-server

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

Related

SQL Server returns wrong result with trailing spaces in Where clause [duplicate]

In SQL Server 2008 I have a table called Zone with a column ZoneReference varchar(50) not null as the primary key.
If I run the following query:
select '"' + ZoneReference + '"' as QuotedZoneReference
from Zone
where ZoneReference = 'WF11XU'
I get the following result:
"WF11XU "
Note the trailing space.
How is this possible? If the trailing space really is there on that row, then I'd expect to return zero results, so I'm assuming it's something else that SQL Server Management Studio is displaying weirdly.
In C# code calling zoneReference.Trim() removes it, suggesting it is some sort of whitespace character.
Can anyone help?
That's the expected result: in SQL Server the = operator ignores trailing spaces when making the comparison.
SQL Server follows the ANSI/ISO SQL-92 specification (Section 8.2, , General rules #3) on how to compare strings with spaces. The ANSI standard requires padding for the character strings used in comparisons so that their lengths match before comparing them. The padding directly affects the semantics of WHERE and HAVING clause predicates and other Transact-SQL string comparisons. For example, Transact-SQL considers the strings 'abc' and 'abc ' to be equivalent for most comparison operations.
The only exception to this rule is the LIKE predicate. When the right side of a LIKE predicate expression features a value with a trailing space, SQL Server does not pad the two values to the same length before the comparison occurs. Because the purpose of the LIKE predicate, by definition, is to facilitate pattern searches rather than simple string equality tests, this does not violate the section of the ANSI SQL-92 specification mentioned earlier.
Source
Trailing spaces are not always ignored.
I experienced this issue today. My table had NCHAR columns and was being joined to VARCHAR data.
Because the data in the table was not as wide as its field, trailing spaces were automatically added by SQL Server.
I had an ITVF (inline table-valued function) that took varchar parameters.
The parameters were used in a JOIN to the table with the NCHAR fields.
The joins failed because the data passed to the function did not have trailing spaces but the data in the table did. Why was that?
I was getting tripped up on DATA TYPE PRECEDENCE. (See http://technet.microsoft.com/en-us/library/ms190309.aspx)
When comparing strings of different types, the lower precedence type is converted to the higher precedence type before the comparison. So my VARCHAR parameters were converted to NCHARs. The NCHARs were compared, and apparently the spaces were significant.
How did I fix this? I changed the function definition to use NVARCHAR parameters, which are of a higher precedence than NCHAR. Now the NCHARs were changed automatically by SQL Server into NVARCHARs and the trailing spaces were ignored.
Why didn't I just perform an RTRIM? Testing revealed that RTRIM killed the performance, preventing the JOIN optimizations that SQL Server would have otherwise used.
Why not change the data type of the table? The tables are already installed on customer sites, and they do not want to run maintenance scripts (time + money to pay DBAs) or give us access to their machinines (understandable).
Yeah, Mark is correct. Run the following SQL:
create table #temp (name varchar(15))
insert into #temp values ('james ')
select '"' + name + '"' from #temp where name ='james'
select '"' + name + '"' from #temp where name like 'james'
drop table #temp
But, the assertion about the 'like' statement appears not to work in the above example. Output:
(1 row(s) affected)
-----------------
"james "
(1 row(s) affected)
-----------------
"james "
(1 row(s) affected)
EDIT:
To get it to work, you could put at the end:
and name <> rtrim(ltrim(name))
Ugly though.
EDIT2:
Given the comments abovem, the following would work:
select '"' + name + '"' from #temp where 'james' like name
try
select Replace('"' + ZoneReference + '"'," ", "") as QuotedZoneReference from Zone where ZoneReference = 'WF11XU'

Searching for records with where clause having single quotes

I have a table column(nvarchar type) which contains an entry "XYZ INT'ABC" and I am using this column in a stored procedure in the where clause. So when adding the condition in the where clause, the check should be done as below:
select * from tableName where ColumnName = 'XYZ INT''ABC';
When passing the parameter to the SP from VB.net code, the parameter is passed correctly as shown in the select query above. But the SP searches using the below query due to which I am not getting the desired output for the mentioned where clause.
select * from tableName where ColumnName = 'XYZ INT''''ABC';
Please help. Thanks in advance.
You've got some suggestions in comments already. Just some explanation:
The doubled quotes are not really part of the string
DECLARE #SomeString VARCHAR(100) = 'With one quote''!';
The string you'll find within your variable will be With one quote'!. The doubled quotes are just a syntax speciality to allow the statement parser to see, whether a quote terminates the string or not. Something like
DECLARE #SomeString VARCHAR(100) = 'With one quote'!'; --wrong!
...is wrong, because the string ends after quote and the !' is a syntax error suddenly.
You need this only in cases, where the single quote is the string marker. In VB.Net you'd have the same issue, if you want to place a double quote " within your string, but this would work in SQL like here:
DECLARE #SomeString VARCHAR(100) = 'With one double quote"!';
You must think two-folded
How do you assign a value? (depending on your IDE and statement parser)
What is the actual value stored in a variable (this will be used at run-time)
Related and more obvious example:
Very often you see code like this (assignment)
string SomeString = "Some text/nwith a line-break";
which is translated to (actual value)
Some text
with a line-break

Hiberante and SQL Server Column name

I have a database that uses "-" in it's columns names.
Example
system-test-id
I mapped the table in Hibernate, but when I try to select all, for example, I get this error:
Invalid column name "system"
Notice that only the first word is taken as column name.
Option show_sql in hibernate shows me this:
select this_.system-test-id as system1_0_0_ (...)
EDIT
I had to add \" in the column name on mapping:
#Id
#Column(name="\"system-test-id\"")
private long systemTestId;
#Column(name="\"system-test-id\"") is the JPA defined way to handle quoted identifiers.
Hibernate has a little more friendly syntax using batck-ticks: #Column(name="system-test-id")
The back-ticks (`) or embedded double-quotes indicate the identifier should be quoted and are replaced with dialect-specific identifier quoting.
Please check the difference between
create table #t
(
[id-Column] int
)
and
create table #t
(
id-Column int
)

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

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;

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 .

Resources