MySQL Syntax error for 5.6.17_1 - mysql

I have MySQL 5.6.17_1 and have query that is used for 5.1.xx
select
schtermid,idfptnsubid,d.idfptnid,idflinksetid,
cast(count(distinct cthr) as real)/cast(count(distinct s.schid) as real)*100 as ctr, cast(sum(status) as real)/cast(count(*) as real)*100 as pfiled,
count(distinct s.schid) as schcount
from source.kdm_session as
This complains
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
'real)/cast(count(distinct s.schid) as real)*100 as ctr, cast(sum(status) as' at line 3
Which part is wrong? What should I change to get the same thing to happen?

As per the docs, real is not a valid type:
The type for the result can be one of the following values:
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]

Try this for your calcs:
(count(distinct cthr) * 1.0)/(count(distinct s.schid) * 1.0)*100 as ctr,
(sum(status) * 1.0)/(count(*) * 1.0)*100 as pfiled,

This is rather a mess - you are mixing up the arguments and inventing types. You're also trying to use AS both as a seperator within a call to CAST() and as an alias operator. Since its meaning is contextual it's good practice not to mix and match in the same query.
Formatting part of your query...
cast(
count(distinct cthr) as real)
/ cast(
count(distinct s.schid) as real
)*100 as ctr
, cast(sum(status) as real)
/cast(count(*) as real)*100 as pfiled
Sorry - but this is so messed up I haven't a clue what you are trying to do here. You seem to be trying the cast the result of a calulation to a type defined by the result of another calculation. Since the can't all have the same alias I guess you must think that 'real' is a type in MySQL (it isn't). Even if you meant a floatling point number - this is just silly - the result of a count is always an integer. You don't even have the same number of opening and closing brackets.
In addition to NOT using 'AS' within CAST(), and using the valid MySQL types, if you formatted your quesry better and provided examples of inputs and outputs we might have a chance at helping you.

Related

Syntax error when trying to remove trailing zeros in SQL

To avoid cosmetic adjustments in the presentation layer, I need to remove trailing zeros from my data outputs - e.g. in my Hours column I need "2" as opposed to "2.000" or "18.5" as opposed to "18.500".
Having reviewed existing resources, I've come up with the following:
SELECT
DATE_FORMAT(U.START_TIME + INTERVAL 1 hour, '%H:%i') as Start
, DATE_FORMAT(U.END_TIME + INTERVAL 1 hour, '%H:%i') as End
, CAST(CAST(TIMESTAMPDIFF(MINUTE, U.START_TIME, U.END_TIME)/60 as DECIMAL (6,2)) as FLOAT) as Hours
, REQUESTER_COMMENT as Requester_Commment
FROM VW_USER_SCHEDULE_INSTANCES U
I keep getting the error message:
Error Code: 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 'FLOAT), REQUESTER_COMMENT as Requester_Comment
I'm struggling to work out what needs to be adjusted to avoid the error. Trying to integrate float is preventing any outputs. Apologies if I'm missing something obvious - I'm a total SQL beginner. Any assistance would be much appreciated!
You should get into the habit of reading the documentation for functions like CAST(). See https://dev.mysql.com/doc/refman/5.7/en/cast-functions.html#function_cast
If you read the docs, you would learn that CAST() doesn't support FLOAT as a destination type. You can use BINARY, CHAR, DATE, DATETIME, DECIMAL, JSON, NCHAR, SIGNED INTEGER, TIME or UNSIGNED INTEGER. But not FLOAT or DOUBLE.
I suggest you try the ROUND() function. See https://dev.mysql.com/doc/refman/5.7/en/mathematical-functions.html#function_round
But my preferred answer is that you should use SQL for fetching raw data, and do formatting for a given presentation in your application code.
Just use to_seconds():
SELECT DATE_FORMAT(U.START_TIME + INTERVAL 1 hour, '%H:%i') as Start,
DATE_FORMAT(U.END_TIME + INTERVAL 1 hour, '%H:%i') as End,
(TO_SECONDS(U.END_TIME) - TO_SECONDS(U.START_TIME)) / (60*60) as Hours,
REQUESTER_COMMENT as Requester_Commment
FROM VW_USER_SCHEDULE_INSTANCES U;
You can format it however you like.

cfm websql queries error

I have this websql script (http://pastebin.com/gvJseBAn) which doesn't perform correctly.
If I run the statement select * from news where id=0772348890 , I get the error The conversion of the varchar value ' 0017707787068' overflowed an int column.
If I run the statement select * from news where id='0772348890' , I get the error Incorrect syntax near '0772348890'.
If I run the statement select * from news where id="0772348890" , I get Invalid column name '0772348890'
Any other variation of '#0772348890#' or #0772348890# or "#0772348890#" I have tried gives the error "incorrect column" or "incorrect syntax near ..."
Any ideas on how to fix this error, or a better method of creating a simple websql query form?
A) the issue here is that db column will not under any conditions accept "0772348890" as a valid input because it is mismatched. The column is an "int" type (according to your first error), but your value has a padded 0 prependedto the front as in 0 772...
What is the purpose of this zero? Ordinarily prepended zeros appear in fixed length character fields where a space is not allowed. Should the value not be "772348890"?
B) Remember that ColdFusion will escape your single quotes in your query. In your second error example (where you use single quotes), this code:
<cfquery name="runsql" datasource="#Form.datasource#" timeout="30">
#Form.sql#
</cfquery>
Produces this SQL statement:
select * from news where id=''0772348890''
Which would give you your syntax error. If you wish to successfully test your second example you will need to alter your code to:
<cfquery name="runsql" datasource="#Form.datasource#" timeout="30">
#preservesinglequotes(Form.sql)#
</cfquery>
Preservesinglequotes() gets you past the second error issue and MSSQL's implicit conversion may strip off the prepended zero and allow the query to succeed - though I'm not sure will give you what you want.
C) Finally you should probably never do what you are trying to do - at least not in this fashion (sorry to be so direct!). Your opening up your DB to arbitrary queries from a web form. The resulting damage from even casual mistakes could be catastrophic to your data, let alone a malicious user bent on stealing or altering or using your site for malicious purposes. That's my take. :)

case statement in MS Access query give error

I am using below query in Ms Access. And this gives me error Syntax error in your query expression CASE WHEN not ... . Can you please tell me what I am doing wrong? In Sql Server 2008 R2, the case statement runs correctly.
SELECT TableApron.RadButtonNo, TableApron.ShortName, QueryForNot1.InspectionDate, QueryForNot1.Findings, QueryForNot1.Status, QueryForNot1.Initials, TableApron.DeptName, TableApron.Lost, TableApron.InServelDate, TableApron.RemovedDate, TableApron.PrivateUserName, TableApron.PrivateUserEmail, TableApron.ApronType, TableApron.Manufacturer
FROM TableApron LEFT JOIN QueryForNot1 ON TableApron.RadButtonNo=QueryForNot1.RadButtonNoI
WHERE (((TableApron.Lost)="N" Or (TableApron.Lost)=[#Lost]) And ((TableApron.InServelDate) Is Null Or (TableApron.InServelDate) Between CDATE([#From]) And CDATE([#To]) Or (TableApron.InServelDate)<CDATE([#To])) And ((TableApron.RemovedDate) Is Null Or (TableApron.RemovedDate) Between CDATE([#From]) And CDATE([#To]) Or (TableApron.RemovedDate)>CDATE([#To])))
ORDER BY
CASE
WHEN not TableApron.RadButtonNo like '%[^0-9]%' THEN CONVERT(int,TableApron.RadButtonNo)
WHEN TableApron.RadButtonNo like '[0-9]%' THEN CONVERT(int,SUBSTRING(TableApron.RadButtonNo,1,PATINDEX('%[A-Z]%',TableApron.RadButtonNo)-1))
END,
CASE
WHEN not TableApron.RadButtonNo like '%[^0-9]%' THEN NULL
WHEN TableApron.RadButtonNo like '[0-9]%' THEN SUBSTRING(TableApron.RadButtonNo,PATINDEX('%[A-Z]%',TableApron.RadButtonNo),9000)
ELSE TableApron.RadButtonNo
END;
The CASE statement triggers the first reported error because it is not supported in Access SQL. Use IIf() instead as #Gustav suggested.
However then you will encounter additional errors because CONVERT, SUBSTRING, and PATINDEX are also not supported in Access SQL.
Instead of CONVERT, use CInt() to cast a value to Access Integer or CLng() for Long Integer. Or you could use Val() and let Access decide which numeric datatype to give you.
Instead of SUBSTRING, use Mid().
Instead of PATINDEX, use InStr().
Assuming those suggestions eliminate the syntax errors, you may still have an issue with the Like wildcard.
If you will be running the query from the query designer or elsewhere under DAO, Access expects * instead of % as the wildcard. % is the correct wild card only when the query is run from ADO/OleDb.

SSRS casting a parameter to decimal multi select

Im trying to cast a parameter in SSRS to a decimal. I have a in clause since its multi select. I can select 1 and it runs fine however if i select more than 1 it will say
"Incorrect syntax near the keyword 'as'."
I am casting my parameter in my where clause in my query statement.
WHERE LOAD_NO IN (CAST(#Load as DECIMAL))
I am confused as to why it would bring back the syntax error if I select more than one from list.
Thanks
I am confused as to why it would bring back the syntax error if I
select more than one from list.
Short answer
Because WHERE LOAD_NO IN (CAST(1,2,N as DECIMAL)) is not a valid T-SQL statement.
Long answer
When you use a multi-value parameter in a query, reporting services will generate different queries if your parameter contains 1 value, or multiple values.
Let's simplify your example to the following query:
SELECT * FROM TABLE WHERE LOAD_NO IN (#Load)
With only one value, the query will have the following format:
exec sp_executesql N'SELECT * FROM TABLE WHERE LOAD_NO IN (#Load)', N'#Load int', #Load=<YourValue>
It's a query with a parameter: #Load.
Now, with multiple values, the query will become
exec sp_executesql N'SELECT * FROM TABLE WHERE LOAD_NO IN (<YourValue1>, <YourValue2>,<YourValueN>)'
The #Load parameter has been replaced by the list of values.
So now my advise will be to rethink the design of your query and treat #Load as a list of values.
We cannot provide you the best solution because it really depends on the data and only you have all the details but I could still throw some ideas.
On the top of my head I could think of:
Cast LOAD_NO instead, but the execution plan may loose the benefits of indexes if any.
In most cases, using a IF EXISTS when possible instead of IN.
Use a subquery.
Do not hesitate to run a SQL Server Profiler to see the generated query if you have other issues.
I'm not sure what your data looks like, so I'm not sure if these options would help, but here's a couple suggestions:
Try putting the CAST on LOAD_NO instead:
WHERE CAST(LOAD_NO AS VARCHAR) IN (#Load)
Create a splitString function like the accepted post here (T-SQL split string) and access it in your WHERE clause:
WHERE LOAD_NO IN (SELECT CAST(val AS DECIMAL) FROM dbo.splitString(#Load, ','))

Select query returns false result

eg:
Table : user
column : user_id (type is int)
SELECT * FROM user WHERE user_id = '10xyz'
is giving same result of
SELECT * FROM user WHERE user_id = '10'
The input value is not integer but not giving an error in this case.
The reason why you are getting the same result is because MySQL automatically removes the trailing characters from the string and implicitly converts it to integer.
SQLFiddle Demo
SQLFiddle Demo (updated)
If you don't want to change all your code, but you have your database queries all going through one or a few subs, you can change those to check for warnings after using a statement handle (e.g. if ( $sth->{mysql_warning_count} ) ...).
Or you can create a DBI subclass that does that automatically for you, promoting warnings to errors. If you do, many others have use for such a thing. There are configuration settings to give an error instead of a warning when updating or inserting something like '10xyz' into an integer field, but not anything broader than that, and dear Oracle considers it Not a Bug. Maybe MariaDB does (or could do) better?
datatype of user_id is in database is INT
that why it giving same output and not error