SQL syntax in openquery - apostrophes inside query - sql-server-2008

I have the following issue, I trying to obtain data via linked server in sql server 2008 from BMC Remedy
Everything is fine with connection, but when I added WHERE
"Assigned Group" LIKE '*scri%'*, I get error in sql server because of apostrophes which I have to use because BMC Remedy demands it.
Do you know how to create correct syntax or force sql server to use quotation marks instead of apostrophes, or disable spell checking
SELECT *
FROM OPENQUERY(Remedy,
**'**
SELECT
Incident_Number
FROM
HPD_Help_Desk
WHERE
"Assigned Group" LIKE ' scri% '
**'**
)

When doing SQL queries from within Remedy, I usually create a new field and use workflow to build the SQL query.
Also the syntax of the where clause you specified isn't correct. Try this instead:
SELECT
Incident_Number
FROM
HPD_Help_Desk
WHERE
Assigned_Group LIKE 'scri%'

There maybe a white spaces that cause you a problems.
You can also try this one:
SELECT Incident_Number
FROM HPD_Help_Desk
WHERE Assigned_Group LIKE '%scri%'
Or you can try to run this one if you run sql on DB:
SELECT r.Incident_Number
FROM ARADMIN.HPD_Help_Desk as r
WHERE r.Assigned_Group LIKE '%scri%'
Because you're running OPENQUERY, maybe double apostrophes will be needed or double quotes instead of one quote (" intead of ').
Good Luck

Related

I'm having difficulties in manipulating records from MySQL database

I'm having difficulties in retrieving and displaying records from a table in a database. I'm using a MySql database and VB.NET 2012.
I'm getting the following error message
"End of statement expected"
Remove the space between Form2 and _Load. Your SQL statement is also broken, the AND being in blue shows this. You have your single and double quotes confusing it, the statement is being ended before the AND due to incorrect syntax. In any case, you should, probably, be using
"SELECT * FROM bigregdb WHERE regID = '"1"' OR regID = '"2"'"

Replace Apostrophe with double Apostrophe

I've recently been asked to look into SQL for the first time and have come across an issue which i cant figure out and was hoping to seek help, i have two SQL servers both running Microsoft SQL Server 2008 and Server A has a linked server to Server B,
a trigger exists which sends data into a stored procedure which then passes the data on insert from server A to server B and this data has names in, the problem i am facing is that names like O'Neil are failing due to the apostrophe and i cant figure out how to replace the apostrophe with double apostrophe's when the data im harvesting is only available from the 'inserted' table.
my trigger is as follows:
SELECT #PassengerName=PassengerName, #DocumentType=DocumentType, #BoardingSequenceNumber=BoardingSequenceNumber,
#FlightNumber=FlightNumber, #CarrierCode=CarrierCode, #DepartureTime=DepartureTime, #Destination=Destination, #DeviceAddress=DeviceAddress,
#Timestamp="Timestamp", #WorkstationId=WorkstationId, #DeliveredTimeStamp=DeliveredTimeStamp from inserted;
SELECT #cmd = 'sqlcmd -S '+##SERVERNAME+' -E -d '+DB_NAME()+' -Q "exec SP_transfer #PassengerName='''+#PassengerName+''',#DocumentType='+#DocumentType+
',#BoardingSequenceNumber='+cast(#BoardingSequenceNumber as varchar(20))+
',#FlightNumber='+#FlightNumber+',#CarrierCode='+#CarrierCode+
',#DepartureTime='''+cast(#DepartureTime as varchar(20))+''',#Destination='+#Destination+
',#DeviceAddress='+#DeviceAddress+''',#TimeStamp='+cast(#Timestamp as varchar(32))+
''',#WorkstationId='+#WorkstationId+',#DeliveredTimeStamp='''+cast(#DeliveredTimeStamp as varchar(50))+'''"';
how can i make it so that the passengername column replaces any apostrophes without breaking the trigger but before it attempts to fire? i appologies if this question seems stupid, but as i mentioned im pretty new to this line of work,
thank you for your time,
Craig
Im not sure if you want to remove or replace the apostrophes in the select. There is a replace function in SQL replace(string, replacestring, replacewith)
SELECT replace('test','est', 'aste')
returns
Taste
So depending on the fields you are using you can strip out the apostrophes on the select of the trigger.
SELECT
#PassengerName=replace(PassengerName,'''',''),
#DocumentType=replace(DocumentType,'''',''),
#BoardingSequenceNumber=replace(BoardingSequenceNumber,'''',''),
#FlightNumber=replace(FlightNumber,'''',''),
#CarrierCode=replace(CarrierCode,'''',''),
#DepartureTime=replace(DepartureTime,'''',''),
#Destination=replace(Destination,'''',''),
#DeviceAddress=replace(DeviceAddress,'''',''),
#Timestamp="Timestamp",
#WorkstationId=WorkstationId,
#DeliveredTimeStamp=DeliveredTimeStamp
from inserted;
If you don't want to remote the apostrophes you could double them up in the same way.

Rails & MySQL: SELECT Statement Single vs. Double Quotes

I have a CRON job which executes a SELECT statement to grab records. When the SELECT runs on my dev machine, it produces the following statement:
SELECT `users`.* FROM `users` WHERE `users`.`id` = 87 LIMIT 1
This is successful.
When the SELECT runs on my production (hosted) machine it produces the statement with double quotes:
SELECT "users".* FROM "users" WHERE "users”.”id” = 87 LIMIT 1
This is not successful and I get a MySQL 1064 error,
#1064 - 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 '.* FROM "users" WHERE "users
The code is the same on both machines, but my dev MySQL is version 5.5.33, whereas production is 5.1.67 (I don't have control over this to set/update it)
Is there a way to force single quotes or another preferred method to handle this situation?
Thanks for your time and assistance.
--EDIT--
Here are the main code snippets that are invoked via my CRON job:
/lib/tasks/reports.rake
namespace :report do
desc "Send Daily Report"
task :daily => :environment do
User.where(:report_daily => 1).find_each do |user|
ReportsMailer.send_report(user, 'daily').deliver
end
end
/app/mailers/reports_mailer.rb
def send_report(user, date_increment)
#user = user
#date_increment = date_increment
get_times(user)
mail :to => user.email, :subject=> "Report: #{#dates}"
end
--EDIT2--
So it looks like I need to use slanted single quotes (`) in order for this to work successfully. How do I force my app or MySQL to use these instead of double (") quotes?
I don't know why it does this, but I do know that if you're referencing column names in MYSQL, you need to use ``, whereas values / data should be wrapped in "", like this:
SELECT `users`.* FROM `users` WHERE `users`.`id` = "87" LIMIT 1
I learnt this the hard way back in the day when I was learning how to do simple MYSQL queries
Here's some documentation from MYSQL's site for you:
The identifier quote character is the backtick (“`”):
mysql> SELECT * FROM `select` WHERE `select`.id > 100;
Identifier quote characters can be included within an identifier if
you quote the identifier. If the character to be included within the
identifier is the same as that used to quote the identifier itself,
then you need to double the character. The following statement creates
a table named a`b that contains a column named c"d:
mysql> CREATE TABLE `a``b` (`c"d` INT);
Is there any reason you couldn't put some of your sql statement directly into your code like:
User.where("`report_daily`=1").find_each do |user|
After further inspection, and working with my hosting company, its turns out that my query is timing out on their server. Thanks to all that responded.
Since you are not using any literals, the format of the generated SQL statements should be determined by the underlying adapter. Perhaps you have a different mysql adapter installed or configured on each machine. Check the installed version. For example:
bundle show mysql
and also check the adapter configuration for your project in database.yml. For example:
adapter: mysql
A comparison of the results of these checks between each machine should tell you if you are using different adapters on the two machines.

Hibernate SQL Injection

I'm auditing a project and I found a way to inject data in a query.
The project uses Hibernate and for this piece of code Session.createSqlQuery() and then a .list()
The SQL is something like : "SELECT * FROM tablename ORDER BY column XXXXXX"
XXXXXX can be modified using Fiddler. So I tried
SELECT * FROM tablename ORDER BY column DESC; truncate table tablename;
Unfortunately (well only for my injection attempt) it's not working and I'm getting :
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 'truncate table tablename'
My question is, since they're using createSQLQuery, are they safe from injection. If they're not, could you give me an example to highlight the issue.
I tried using %08 (Backspace character) thinking I would be able to delete previous query characters for example (It didn't work ;) )
Thanks.
After some research it seems I won't be able to modify data with this security hole, however using ORDER BY (CASE WHEN ...) would allow to "scan" the tables and the data.
Is the column name specified using a parameterized statement or are you just concatenating text?
ex: in perl::DBI, the drivers support the following syntax:
$dbh->do("SELECt * FROM asdf ORDER BY ?", undef, $order_by);
The ? there is a form of parameterized statement which sanitizes the input automatically.

MySQL: CONCAT_WS function is running on local but not on server

Some days ago I asked a question about my problem and I was advised to use CONCAT_WS function. I am using CONCAT_WS on my local mysql database and it is working perfectly. But it is not working on server(application hosted) and generate the following error.
FUNCTION test.CONCAT_WS does not exist
Here test in error string is my database name on server.
My query is like this:
SELECT * FROM patient WHERE CONCAT_WS (',', LastName,FirstName,BirthDate ) NOT IN ('Abdul,Quddus,2000-09-30','Wasim,Akram,1993-09-12');
Can someone tell me the problem or suggest me another solution asked in linked question above ?
Thanks
The easiest way to fix it is by removing the whitespace between the function name and the parenthesis, i.e. CONCAT_WS(...) instead of CONCAT_WS (...).
From the MySQL Manual:
By default, there must be no
whitespace between a function name and
the parenthesis following it. This
helps the MySQL parser distinguish
between function calls and references
to tables or columns that happen to
have the same name as a function.
...
You can tell the MySQL server to
accept spaces after function names by
starting it with the
--sql-mode=IGNORE_SPACE option.
Also, this behavior depends on the MySQL version, this is why it works on one server and doesn't work on another, quote from the "Function Name Parsing and Resolution" manual page:
The number of function names affected
by IGNORE_SPACE was reduced
significantly in MySQL 5.1.13, from
about 200 to about 30.