DECODE Function in SQL - mysql

I am trying to insert the following query and I get syntax errors. Can you please help me with the below query:
INSERT INTO ABCTABLE (COLUMN1) values ('DECODE(MDSE_CD,NULL,'0000000000000000',LPAD(TO_NUMBER(MDSE_CD,'16',' '))');

Since you haven't really said anything other than "this query doesn't work, fix it", I have to take a stab in the dark what you want. From the query you have, I'm therefore guessing you want the value of the column to be DECODE(MDSE_CD,NULL,'0000000000000000',LPAD(TO_NUMBER(MDSE_CD,'16',' '))
In which case, you have to escape the single quotes within your string literal. Do this by doubling up the quotes:
INSERT INTO ABCTABLE (COLUMN1)
VALUES ('DECODE(MDSE_CD,NULL,''0000000000000000'',LPAD(TO_NUMBER(MDSE_CD,''16'','' ''))')

Try properly escaping the inner single quotes
INSERT INTO ABCTABLE (COLUMN1)
VALUES ('**DECODE**(MDSE_CD,NULL,''0000000000000000'',**LPAD**(TO_NUMBER(MDSE_CD,''16'','' ''))');

The problem is the use of quote marks. If we tried to break up your query it would look like this:
INSERT INTO ABCTABLE
(COLUMN1)
values
(
'DECODE(MDSE_CD,NULL,'
0000000000000000
',LPAD(TO_NUMBER(MDSE_CD,'
16
','
'))'
);
...which clearly makes no sense.
You might want to think about how to escape a quote mark inside a string.

Sql Server:
DECOD function in Sql Server can be replaced with CASE construct
LPAD function in Sql Server has not a direct correspondence but you can pad your string using string manage function REPLACE (replicate a character a number of specified times)
My Sql:
DECOD function in MySql can be replaced with CASE construct
LPAD function in MySql is existent

What do you want to store... a string literal 'DECODE(MDSE...))', or did you want to call a function to derive a value?
To store a string literal containing single quotes, you need to "escape" each single quote within the string with an extra single quote, e.g.
O'Hare Int'l ==> 'O''Hare Int''l'
The DECODE function is Oracle specific. That expression will need to be rewritten using different functions in both MySQL and SQL Server.

Related

sql server equivalent of mysql where in

I have always used a MySQL Where In to filter for multiple values of a single field. I am looking for the equivalent for SQL Server. When I set this up on SS it looks at each item as a field in my table instead of a record in my field. Does anyone know the equivalent? Thanks!
MySQL:
SELECT quote_id,entity_id FROM customer.customer_id4
WHERE
quote_id IN ("00033658.0","00033361.0","00032971.0")
Error when using similar format in SS:
Invalid column name '00033658.0'
Invalid column name '00033361.0'
Invalid column name '00032971.0'
" in SQL server is used to delimit field names. You need to use ' instead, e.g.
... quote_id IN ('00033658.0', '00033361.0', etc...)
^-- ^--- note the different quotes
I think you just have to replace double quotes(") with a single quote (').
SELECT quote_id,entity_id FROM customer.customer_id4
WHERE
quote_id IN ('00033658.0','00033361.0','00032971.0')
Try using single quotes in the IN statement and see this link: http://technet.microsoft.com/en-us/library/ms177682.aspx

Add quotes in stored procedure

I have a stored procedure whereby text is the input. Is it possible to accept text without quotes and then through the replace function insert single quotes inside the procedure?
Use MySQL's QUOTE() function:
Quotes a string to produce a result that can be used as a properly escaped data value in an SQL statement. The string is returned enclosed by single quotation marks and with each instance of backslash (“\”), single quote (“'”), ASCII NUL, and Control+Z preceded by a backslash. If the argument is NULL, the return value is the word “NULL” without enclosing single quotation marks.
mysql> SELECT QUOTE('Don\'t!');
-> 'Don\'t!'
mysql> SELECT QUOTE(NULL);
-> NULL
If you know where and how to put back the quotes, it is possible.
If I understand correctly that you want to be able to write, for example:
foo(All human beings are born free and equal in dignity and rights.)
and have it be interpreted as:
foo('All human beings are born free and equal in dignity and rights.')
then — no. This is not possible.

mysql: replace \ (backslash) in strings

I am having the following problem:
I have a table T which has a column Name with names. The names have the following structure:
A\\B\C
You can create on yourself like this:
create table T ( Name varchar(10));
insert into T values ('A\\\\B\\C');
select * from T;
Now if I do this:
select Name from T where Name = 'A\\B\C';
That doesn't work, I need to escape the \ (backslash):
select Name from T where Name = 'A\\\\B\\C';
Fine.
But how do I do this automatically to a string Name?
Something like the following won't do it:
select replace('A\\B\C', '\\', '\\\\');
I get: A\\\BC
Any suggestions?
Many thanks in advance.
You have to use "verbatim string".After using that string your Replace function will
look like this
Replace(#"\", #"\\")
I hope it will help for you.
The literal A\\B\C must be coded as A\\\\A\\C, and the parameters of replace() need escaping too:
select 'A\\\\B\\C', replace('A\\\\B\\C', '\\', '\\\\');
output (see this running on SQLFiddle):
A\\B\C A\\\\B\\C
So there is little point in using replace. These two statements are equivalent:
select Name from T where Name = replace('A\\\\B\\C', '\\', '\\\\');
select Name from T where Name = 'A\\\\B\\C';
Usage of regular expression will solve your problem.
This below query will solve the given example.
1) S\\D\B
select * from T where Name REGEXP '[A-Z]\\\\\\\\[A-Z]\\\\[A-Z]$';
if incase the given example might have more then one char
2) D\\B\ACCC
select * from T where Name REGEXP '[A-Z]{1,5}\\\\\\\\[A-Z]{1,5}\\\\[A-Z]{1,5}$';
note: i have used 5 as the max occurrence of char considering the field size is 10 as its mentioned in the create table query.
We can still generalize it.If this still has not met your expectation feel free to ask for my help.
You're confusing what's IN the database with how you represent that data in SQL statements. When a string in the database contains a special character like \, you have to type \\ to represent that character, because \ is a special character in SQL syntax. You have to do this in INSERT statements, but you also have to do it in the parameters to the REPLACE function. There are never actually any double slashes in the data, they're just part of the UI.
Why do you think you need to double the slashes in the SQL expression? If you're typing queries, you should just double the slashes in your command line. If you're generating the query in a programming language, the best solution is to use prepared statements; the API will take care of proper encoding (prepared statements usually use a binary interface, which deals with the raw data). If, for some reason, you need to perform queries by constructing strings, the language should hopefully provide a function to escape the string. For instance, in PHP you would use mysqli_real_escape_string.
But you can't do it by SQL itself -- if you try to feed the non-escaped string to SQL, data is lost and it can't reconstruct it.
You could use LIKE:
SELECT NAME FROM T WHERE NAME LIKE '%\\\\%';
Not exactly sure by what you mean but, this should work.
select replace('A\\B\C', '\', '\\');
It's basically going to replace \ whereever encountered with \\ :)
Is this what you wanted?

MySQL LONGTEXT doesn't accept an apostrophe '

I was building a portal for my college with posting messages option. Hence I used LONGTEXT to store the message in mysql. But somehow the LONGTEXT doesn't accept the apostrophe mark.
It gives following error whenever I post some sentence with apostrophe mark:
"Error: 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 's open singles
tournament, will Electrical be able to maintain their dominance o' at line 1"
PS: not in the escape string, but in <textarea>, if I input the apostrophe mark it gives the error!
Escape it with a backslash like
SELECT 'This is a escape \' quote test';
EDIT
If you are taking information directly from a web form and inserting it into a data base - this is a massive security risk. This is how SQL injection is done.
You have two problems.
You copied the value of the long text into your 'query' (presumably an INSERT or UPDATE statement, though it could simply be the value to compare with in a SELECT).
You did not notice that the first unescaped single quote after the opening quote terminates the string.
Given that you are using MySQL, I believe you have two options on escaping:
Standard SQL (applies to most, if not all, SQL DBMS): use two consecutive single quotes to insert one:
'''' -- Insert a string consisting of one single quote
'He said, "Don''t do that!"' -- A string containing a single quote
MySQL (may also be an option elsewhere, but not every SQL DBMS will recognize it): use a backslash to escape the single quote:
'\'' -- As above
'He said, "Don\'t do that!"' -- Also as above
There may also be functions you can use to do the escaping for you - depending on the host language you are using. However, the preferred way to get values into an SQL statement, especially ones that might contain random characters, is to use placeholders. The mechanics depend on the host language in which you are embedding the SQL, but the general idea is:
The raw SQL string looks like: INSERT INTO SomeTable VALUES(?, ?, ?);
You PREPARE the statement, more or less explicitly.
When you execute it, you provide the data as parameters to the EXECUTE.
Or, if it is a SELECT statement, you PREPARE it, you DECLARE a cursor for it, then you OPEN the cursor and provide the parameter values at that time.
In one SQL-based language (IBM Informix 4GL):
DEFINE a INTEGER, b DECIMAL(10,2), c VARCHAR(250)
LET a = 1
LET b = 99999999.99
LET c = 'He said, "Don''t do that!"'
PREPARE p1 FROM "INSERT INTO SomeTable(a,b,c) VALUES(?, ?, ?)"
EXECUTE p1 USING a, b, c
PREPARE p2 FROM "SELECT * FROM SomeTable WHERE c = ?"
DECLARE c2 CURSOR FOR p2
OPEN c2 USING c
Note that if you do not use placeholders, you have to be extremely careful not to fall into the SQL Injection trap.
use the backslash character to escape the string:
"Carlito\'s Ways"
You may need to unescape later, but PHP has a built-in function for that.
insert into customers(firstname, lastname)
values ('Bill', 'O\'Connor');
I'm assuming you need to escape your apostrophes with a backslash character (\), but it would also be intuitive to provide the SQL query that you attempted to execute in order for people to help you further.

passing string in a query to MySQL database in MATLAB

I am using MySQL with MATLAB, and I want to get a name from user, and pass it to the table in mySQL, but it is rejecting a variable name in place of string
var_name=input('enter the name:');
mysql('insert into table (name) values (var_name)');
Any suggestions?
FIRST read the comments to this question - you don't want to shoot yourself in the foot with a mysql injection security problem. You have been warned. Now, to solve your current problem, without addressing the security risk of the whole approach when it comes to building SQL queries, read on...
In principle Amro has already posted two solutions for you which work, but since you have not accepted it I'll explain further.
Your problem is that you are not telling MATLAB which parts of your query it should interpret as a literal string, and which parts it should interpret as a variable name. To solve this, you can just end the literal string where appropriate, i.e. after the opening brackets, and then start them again before the closing brackets.
In between those literal strings you want to add the contents of your variables, so you need to tell MATLAB to concat your literal strings with your variables, since the mysql command probably expects the whole query as a single string. So in essence you want to take the string 'insert into table(' and the string saved in the variable name and the string ') values (' and so on and glue them into one big string. Amro and Isaac have shown you two solutions of how to do this without much explanation:
horzcat('insert into table (', name, ') values (', var_name, ')')
uses the function horzcat, while
['insert into table (' name ') values (' var_name ')']
uses the fact that MATLAB treats strings as arrays of characters so that you can just use square brackets to form a large array containing the strings one after the other.
The third solution, offered by Amro, is a bit more sublte:
sprintf('insert into table (%s) values (%s)',name,var_name)
It tells the function sprintf (which is made for that purpose) "take the string which I supply as first parameter and replace occurences of %s with the strings I supply as the following parameters. This last technique is in particular useful if you also need to insert numbers into your string, because sprintf can also convert numbers to string and allows fine control over how they are formatted. You should have a close look at the help page for sprintf to know more :-).
Try this instead:
mysql(['insert into table (' name ') values (' var_name ')']);
or even:
mysql(sprintf('insert into table (%s) values (%s)',name,var_name));
I believe the problem you are having is the same as the one in this other question. It sounds like you want to create a command string that itself contains a ' delimited string, which would require you to escape each ' with another ' when you create your command string (note the first example in this string handling documentation). Note also you may want to use the 's' option for the INPUT function:
var_name = input('Enter the name: ','s'); %# Treats input like a string
commandString = sprintf('insert into table (name) values (''%s'')', var_name);
%# Note the two apostrophes --^
mysql(commandString);
If I were to enter Ken for the input, the string commandString would contain the following:
insert into table (name) values ('Ken')
And of course, as others have already mentioned, beware injection vulnerabilities.