SQL Select error and OUTPUT - sql-server

I need to query a database for some information and then store it into a .csv file in case the dispatch system goes down. I'm running into some issues with the select query as well as the output statement. Here is what I have:
SELECT cmpy, veh, driver, attendant, trainee, unit_code, startdate
FROM vehicle_schedule
WHERE startdate >= 2015-07-22
ORDER BY cmpy, veh
The error that I am getting is this:
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value '2010-05-25' to data type int.
I'm not sure what is going on and exactly how to fix the issue. Also I can't get it to output to a file, I get the error: incorrect syntax near 'OUTPUT'
Any help would be amazing!

This is too long for a comment. You are missing single quotes for the date constant:
WHERE startdate >= '2015-07-22'
The error you are getting is because 2015-07-22 = 1986 (they hyphens are interpreted as minus signs), so the query is turned into:
WHERE startdate >= 1986
Because of the comparison to an integer, SQL Server attempts to convert startdate to an integer . . . and you get a relatively unintelligible error.

you missed quotes around the date
try this
SELECT cmpy, veh, driver, attendant, trainee, unit_code, startdate
FROM vehicle_schedule
WHERE startdate >= '2015-07-22'
ORDER BY cmpy, veh

Related

Same code errors in a Stored Procedure, works in T-SQL

I have a stored procedure that calls a linked server like below. The column 'datestr' is of type char(8) and is not always properly formatted. It is usually yyyymmdd but since I do not control how that data is formatted, I am using the TRY_CAST to only get rows where I can format it into a date.
Executing the SP gives me the following error:
Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Running the exact same code extracted from the SP in T-SQL returns data without error. I'm certain the issue is with the part of the WHERE clause with the DATEADD function hitting a value that is not able to be CAST into a date but I can't figure out why it runs differently in SP and extracted T-SQL.
I checked the plan using SET SHOWPLAN_ALL ON before running both and see some variations. Namely the estimated rows in the working query are much lower in the Remote Query operator (~200K vs. 15 mil)
CREATE Procedure [dbo].[SampleSP]
AS
SELECT top 50 tbl1.rowID as rowID,
year(datestr) as [year],
month(datestr) as [month],
count(*) AS CountRow
FROM [LinkedSer].[RemoteDB].[dbo].[tbl1] tbl1
inner join [dbo].[LocalTbl] tbl2 on tbl1.rowID = tbl2.rowID
WHERE tbl1.row_type = 'tbl1A'
and (TRY_CAST(tbl1.datestr AS date) IS NOT NULL
and tbl1.datestr > DATEADD(yy, -10, getdate()))
group BY tbl1.rowID, year(tbl1.datestr), month(tbl1.datestr)
The order the predicates are evaluated is plan-dependent. So you need to eliminate the potentially-invalid comparison from your code.
And simplifying to:
and TRY_CAST(tbl1.datestr AS date) > DATEADD(yy, -10, getdate())
should do the trick.

Trying to convert NVARCHAR column value to DECIMAL(10,2)

I am getting this error when I'm trying to convert all nvarchar values in a specific column in my table and remove the $ from the value as well.
Here is the error:
Msg 8114, Level 16, State 5, Line 7
Error converting data type nvarchar to numeric.
Here is my code:
UPDATE dbo.CMS_BI_Demand
SET DemandAmount = (SELECT CONVERT(DECIMAL(10, 2), REPLACE(DemandAmount, '$', '')) as DemandAmt
FROM dbo.CMS_BI_Demand
WHERE BISysID = 1)
Any help/direction would be appreciated.
Here is my code that corrected the error:
UPDATE dbo.CMS_BI_Demand
SET DemandAmount = t1.DemandAmount
FROM (
SELECT BISysID, CONVERT(DECIMAL(10,2), REPLACE(REPLACE(DemandAmount,'$',''),',','')) as DemandAmount
FROM dbo.CMS_BI_Demand
) t1
WHERE dbo.CMS_BI_Demand.BISysID = t1.BISysID;
Are you sure the values are all numeric after replacing the $? I ran into this once and had to do some data cleanup before I could do the update. In my case, there was a space in one of the rows so it failed. As soon as I fixed the record, everything worked.
You didn't specify what sql you're running but if you're using Microsoft SQL, I would run a check using isnumeric and verify that nothing returns as false:
SELECT id, ISNUMERIC(REPLACE(DemandAmount,'$','')) as DemandAmt
FROM dbo.CMS_BI_Demand
WHERE BISysID = 1 AND ISNUMERIC(REPLACE(DemandAmount,'$','')) = 0
Different cultures have different decimal and thousand separators. When you call CONVERT the server will use the locale specified through the LANGUAGE setting to try and parse the string. At best, if the string and locale don't match, you'd get an error. The worst case is that the string will be passed using the wrong separator.
Given the $ symbol, it looks like you're trying to parse a US-style numeric string in a non-US locale. The solution is to use PARSE or TRY_PARSE with en-us as the culture :
select parse('234.5' as numeric(10,2) using 'en-us')
You can avoid trimming the currency sign if you parse to money first :
select parse('$234.5' as money using 'en-us')
DON'T try to replace separators. This can easily lead to wrong values and still fail to parse the text. What if the value was 2,345.123? Even if you remove the thousand separator, trying to convert this value eg in Germany would produce 2345123.00 :
select parse('2345.123' as decimal(10,2) using 'de-DE')
Returns :
2345123.00
You may assume this won't happen in production. How about the EUR/USD exchange rate? In Italy?
SELECT PARSE('1.12' as decimal(10,2) using 'it-IT')
------
112.00
Oops
To figure out what values your SQL SERVER instance can't properly cast to decimal(10,2), use this:
SELECT DemandAmount
FROM dbo.CMS_BI_Demand
WHERE TRY_CONVERT(DECIMAL(10,2), REPLACE(REPLACE(DemandAmount,'$',''),',','')) IS NULL

Converting a MSSQL Datestamp to BIGINT for UNIX

I've been having trouble with something i cannot quite get my head around and I was wondering if you can help?
On my table, i have a column called
ADDEDDATE
This column shows the date in which an incident or ticket was added to the database table and its formatting is shown as the following example:
2015-08-25 09:58:14.967
I want to convert this to UNIX timestamp so first i have performed the following:
SELECT DATEDIFF(SECOND,{d '1970-01-01'}, ADDEDDATE) AS 'UNIX DATE ADDED' FROM dbo.TABLE
Running this I get integer values such as "1147855575". Now I understand in order to make this work on UNIX timestamp i need to use BIGINT to convert, so i wrote the following:
SELECT DATEDIFF(SECOND,{d '1970-01-01'}, ADDEDDATE) AS 'UNIX DATE ADDED',
CASE CAST(SUM('UNIX DATE ADDED' AS BIGINT) FROM dbo.TABLE
This returned an error:
Msg 195, Level 15, State 10, Line 2
'SUM' is not a recognized built-in function name.
So i did some googling and searching through Stackoverflow and found i did the second line wrong, it should look like:
SELECT DATEDIFF(SECOND,{d '1970-01-01'}, ADDEDDATE) AS 'UNIX DATE ADDED',
CASE CAST(BIGINT,'UNIX DATE ADDED') FROM dbo.TABLE
However this too fails with the following message:
Msg 1035, Level 15, State 10, Line 2
Incorrect syntax near 'CAST', expected 'AS'.
Can someone please assist me in trying to convert an entire column of integer data to BIGINT for UNIX Datestamp? I am using MSSQL (SSMS 2014).
Just:
SELECT CAST(DATEDIFF(SECOND, '1970-01-01', ADDEDDATE) AS bigint) AS 'UNIX DATE ADDED' FROM dbo.TABLE;
When you'll migrate on SQL Server 2016, you'll be able to use DATEDIFF_BIG

Query giving error

The below query is giving error, please help me.
declare #dateScorecard datetime
set #dateScorecard = convert(varchar, 4)+'/1/'+ convert(varchar,2013)
select #dateScorecard
select top 1 i_CurrentMonthColor from AK_ScoreCardDetails scr
where datediff(m, convert(Datetime, convert(varchar, 4)+'/1/'+ convert(varchar,2013)), #dateScorecard)
error details:
Msg 4145, Level 15, State 1, Line 5
An expression of non-boolean type specified in a context where a condition is expected, near ')'.
Two quick comments:
First, you don't need to use convert on those numbers--just put them right into your query, i.e.
set #dateScoreCard = convert('4/1/2013');
Also, in the 'where' clause, you are not comparing the result of the datediff to anything There should be a section after the datediff clause, i.e.:
where datediff(.....) > 2
for example. Your datediff function only gives you a number that is the difference of the two dates you gave it, in the terms you define, which is months here. Use that number to compare to some value you want to make your sql statement work for you.

C, unixODBC, oracle and Date queries

I've got a query like
select x from tableName where startDate <= now;
When i query the database without the date fields, everything works as expected. As soon as i start using date or timestamp columns in the oracle Database, my queries return nothing or an error.
What I do:
snprintf(sql, sizeof(sql), "SELECT roomNo, userPass, adminPass, adminFlags, userFlags, bookId, is_locked, running_on_server FROM booking WHERE roomNo = '?' AND startTime <= { ts '?' } AND endTime >= { ts '?' } for update;");
stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
the ? will be replaced by values, with following command:
SQLBindParameter(stmt, i + 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(gps->argv[i]), 0, gps->argv[i], 0, NULL);
when I execute the query I get an error that TS is an invalid identifier [this was a recommendation by another board, taken from msdn - which may cause this error]
but even if I remove it and send just a string to the database, I'll get an empty result back. I also tried to bind the parameters as SQL_TIMESTAMP and SQL_DATE, but this didn't help either.
Hopefully somebody can help me.
thanks in advance.
Chris
Are you sending a DATE data type to the Oracle query or a date represented in a string?
From the Oracle side of things, if you send a date in a string variable you'll need to use the oracle "TO_DATE" function (http://www.techonthenet.com/oracle/functions/to_date.php) to then convert thew string back to a date for use in your SQL statement (assuming startDate or startTime/endTime are DATE columns in the database).
Your fist SQL example should be:
SELECT x
FROM tableName
WHERE startDate <= TO_DATE(now, '<date-format>');
If the variable "now" was a string containing '05-OCT-2011 16:15:23' (including a time portion) then the to_date would be:
TO_DATE(now, 'DD-MON-YYYY HH24:MI:SS')
If you compare a string with a date and don't specify the format of that date Oracle will use its default NLS parameters and try to apply that format. Therefore it is always prudent to specify the date format using TO_DATE.
Hope it helps...

Resources