Sybase datediff produces "data conversion not possible" error - sybase

I am trying to calculate age as of a given YYYYMMDD date (2013-12-13) using an unsigned integer YYYYMMDD date of birth variable (dob) from a Sybase IQ 15.4 database (setdata). It isn't my database and I have no control over how the data are stored.
I am using the following code:
select
convert(date,convert(varchar,dob)) as yearborn,
DATE("2013-12-31") as present,
datediff(month,yearborn,present)/12 as age_in_yrs
from setdata
This works fine in the Interactive SQL tool I have, but when I run it using SAS connect with the same code (so I can get a log) I get this message:
ERROR: CLI execute error: [Sybase][ODBC Driver][Sybase IQ]Data exception - data type conversion is not possible. -- (dfe_Cast.cxx 835)
Update: SAS converts the commands into ANSI SQL. So I think I am looking for an ANSI way to do this, and that my function is not supported.

Related

SQL Server not accepting YYYY-MM-DD

My local SQL Server 2016 setup at work decided not to accept the YMD date format after going through a reinstall. For example, the following query, that was and still is accepted in my coworkers' setups:
SELECT "id"
FROM test.dbo.tabEmp
WHERE "DateAdmission" <= '2021-12-31' AND "DateAdmission">= '2021-12-30' `
When I try to run it I see this:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value
however, if i rewrite the dates as 2021-31-12 and 2021-12-30, in the YYYY-DD-MM format, they are accepted.
I can't really convert or format it since the sql queries in our system are numerous and done so in a way that it would be nearly impossible to. Is there something that can be done? I tried changing windows' Date format but to no avail.
For the datetime and smalldatetime data types the format yyyy-MM-dd is not unambiguous (note that it is for the newer date and time data types). If you are not American, the date will very likely be interpreted as yyyy-dd-MM, and as there are not 31 months in the year you get an error.
For SQL Server, the formats that are unambiguous regardless of data type and language setting are yyyyMMdd and yyyy-MM-ddThh:mm:ss.nnnnnnn; ideally if you are using string literals use one of those formats as you can never get an error (unless you legitimately have an invalid date).
Otherwise you can explicitly CONVERT your value with a style code:
SELECT CONVERT(datetime, '2021-12-31', 126);
It seems that your new DB instance picked up a new language after the reinstallation.
The current language setting determines the language used on all system messages, as well as the date/time formats to use.
The date format setting affects the interpretation of character strings as they are converted
to date values for storage in the database. It does not affect the display of date data type values
that are stored in the database or the storage format.
You can run the following statement to return the language currently being used:
SELECT ##LANGUAGE;
This will tell us what the current language is and the date format (as well as a few other things):
DBCC USEROPTIONS;
Date format is modifiable via the following statements:
SET LANGUAGE us_english;
SET DATEFORMAT YMD;
Here is a good article on the subject: How to Change the Current Date Format in SQL Server (T-SQL)
It is also possible to modify SQL Server instance default language globally, once and for all: How to change default language for SQL Server?

SSIS Web Service Task - Input variable

Im trying to download some data from web services using Web Service Task component in SSIS. Everything works fine when I insert required Input value manually. The required input value have to be in dateTime type but it only works when I munually write datetime in YYYY-MM-DD or YYYY-MM-DD HH:MM format.
But that of course is not what I wanted to do.
So I created a variable with DateTime data type with simple expression:
(DT_DATE) GETDATE()
But that gives me format DD.MM.YYYY HH:MM instead of YYYY-MM-DD or YYYY-MM-DD HH:MM.
When I execute the package it goes into error message:
[Web Service Task] Error: An error occurred with the following error message: "Microsoft.SqlServer.Dts.Tasks.WebServiceTask.WebserviceTaskException: Could not execute the Web method. The error is: Method 'ProxyNamespace.Service.Method' not found..
at Microsoft.SqlServer.Dts.Tasks.WebServiceTask.WebMethodInvokerProxy.InvokeMethod(DTSWebMethodInfo methodInfo, String serviceName, Object connection)
at Microsoft.SqlServer.Dts.Tasks.WebServiceTask.WebServiceTaskUtil.Invoke(DTSWebMethodInfo methodInfo, String serviceName, Object connection, VariableDispenser taskVariableDispenser)
at Microsoft.SqlServer.Dts.Tasks.WebServiceTask.WebServiceTask.executeThread()".
I think its only because my variable is in incorrect format. Any suggestions how to change it to desired dateTime format while data type of variable remains with DateTime option ? Thanks !
EDIT :
So I managed to solve the problem with the DateTime format, I simply changed the date format on my server to YYYY-MM-DD in the Windows environment (Control Panel - Region - Formats) and it also changed in SSIS.
But the problem still persists, when I check the box in the input section that I use a Variable and select my variable in the correct format as a DateTime with the correct value YYYY-MM-DD, I still get an error message and nothing happens.
Do you have any other solutions to my problem?

ADO Recordset Type for Date

Warning: Classic ASP Ahead. :)
I'm working on a legacy Classic ASP application and I'm running into an oddity with an ADODB.Recordset object.
I have a SQL2012 database table containing a particular field. Let's call it AnnoyingField. Its datatype in SQL is 'date'.
The ASP opens an ADODB.Recordset with a SELECT on the table to collect the fields, then does some looping to do its work:
For each Field in rs.Fields
typeid = rs(Field.Name).Type
'do stuff based on type
For some reason, the Type for AnnoyingField is coming back as 202 (nvarchar) rather than one of the expected types for date (133 or even 7). This is causing some issues further in the code.
I tested with another field of 'datetime' type and the Recordset code returned the expected Type for a datetime field.. 135.
Anyone have an idea why the 'date' fields are returning as an nvarchar?
Changing the database fields from date to datetime in this case might not be possible, even though it might be the logical path to take to get expected data.
Date fields are newer than your version of ADODB. So it doesn't understand what it's getting.
You may be able to cheer it up by using
select convert(datetime, AnnoyingField) from CrazyFuturisticTable
You may also get the correct result if you upgrade your ADODB version to 2.8 and/or connect using the SQL Native Client. Obviously, I haven't tried this, because I live in 2014.
If you keep it a little simpler, cut ADO out of the picture and use isdate and "convert date" and vartype.
For each Field in rs.Fields
Field=rs(Field.Name)
if isdate(Field) then Field=cdate(Field) ' just in case
typeid = VarType(Field)
'do stuff based on type
Vartype
http://www.w3schools.com/vbscript/func_vartype.asp
ADO .type can report more "types"
http://www.w3schools.com/ado/prop_para_type.asp
But I think what vartype can offer should help people in 95% of cases.
Word of warning with cdate, depending on what the server locale is set too or your Session.LCID (in your code) is set will determine what format the date will be formatted to. Shouldn't be a problem for most people but obviously test to see if you get the expected result.
I am using Classic ASP / VBScript and have found that for SQL2012 using SQL Native driver ("Provider=SQLNCLI11"), and the ADO module provided by Windows (presumably Vista or newer [mine is Windows Servr2012 R2 - the version [MyDbConn.version] shows as 6.3) this now works again.
I had been looking for / expecting the Field.Type to be adDate [7], but am actually getting adDBDate [133]

how do I import a date like 2009-12-05 11:40:00 into SQL via CSV?

I'm using the Import/Export Wizard to import some data to a table. Total of 2 rows, so I've just been working around this, but I would like to know the answer.
The issue with the Import/Export is the dates. No matter what I do, they fail. The date looks pretty straightforward to me: 2009-12-05 11:40:00. I also tried: 2010-03-01 12:00 PM. Tried DT_DATE and DT_DBTIMESTAMP as a source data type. The target column type is datetime.
The message that I get is:
The data conversion for column
"Start_Date" returned status value 2
and status text "The value could not
be converted because of a potential
loss of data.".
How do I fix this? Why's the Import/Export Wizard so bad at parsing dates (or is that in my imagination)?
The truly obnoxious thing here is that when you select a date column from a table and save it as a CSV you get a date like '2009-12-05 11:40 AM'. So the import wizard isn't even capable of parsing dates that come from SQL Server. Really? Really?
Added details (realized my description wasn't correct after revisiting the package I had issues with):
The import thing IS pretty bad.
In my case I had incoming data with form matching SQL Server type 126 / ISO8601. That is, in T-SQL, this form:
select convert ( varchar(100), getdate(), 126 )
--> 2009-12-22T16:29:22.123
I was able to import with SSIS using two steps:
Replace the "T" with a space " ", using SSIS Derived Column with expression:
REPLACE(DateColumn,"T"," ")
Cast the result to database timestamp [DT_DBTIMESTAMP] using the data conversion transform
Apologies if I caused any confusion.

Executing stored procedures with date parameters: Command Object vs Connection Object

When supplying dates to a stored procedure via a parameter I'm a little confused over which format to use for the dates. My original VBA syntax used the ADO Connection object to execute the stored procedure:
Set SentDetailRS = Me.ADOConnectionToIntegrity.Execute("dbo.s_SelectAggregatedSentDetailList '" & fCSQLDate(EffectiveDate) & "'", , adCmdText)
This works fine for me using the date syntax yyyy-mm-dd but when another user executes the code they recieve the error: 13 'Type Mismatch'.
After some experimentation I found that supplying the date in the format dd/mm/yyyy fixes this error for the user but now gives me the error!
Executing the stored procedure using a command object with parameters works regardless of the format of the date (I assume ADO is taking care of the formatting behind the scenes). I thought that using the format yyyy-mm-dd would work universally with SQL Server?
I'm also perplexed as to why this problem appears to be user specific? I noticed that my default language on SQL Server is 'English' whereas the other user's default language is 'British English', could that cause the problem?
I'm using ADO 2.8 with Access 2003 and SQL Server 2000, SQL Server login is via Windows integrated security.
Be careful, and do not believe that ADO is taking care of the problem. Universal SQL date format is 'YYYYMMDD', while both SQL and ACCESS are influenced by the regional settings of the machine in the way they display dates and convert them in character strings.
Do not forget that Date separator is # in Access, while it is ' in SQL
My best advice will be to systematically convert your Access #MM-DD-YYYY# (or similar) into 'YYYYMMDD' before sending the instruction to your server. You could build a small function such as:
Public function SQLdateFormat(x_date) as string
SQLDateFormat = _
trim(str(datePart("yyyy",x_date))) & _
right(str(datePart("m",date)),2) & _
right(str(datePart("d",date)),2)
''be carefull, you might get something like '2008 9 3'
SQLDateFormat = replace(functionSQLDateFormat," ","0")
'' you will have the expected '20080903'
End function
If you do not programmatically build your INSERT/UPDATE string before sending it to the server, I will then advise you to turn the regional settings of all the machines to the regional settings of the machine hosting SQL. You might also have to check if there is a specific date format on your SQL server (I am not sure). Personnaly, I solved this kind of localisation problems (it also happens when coma is used as a decimal separator in French) or SQL specific characters problems (when quotes or double quotes are in a string) by retreating the SQL instructions before sending them to the server.
I would guess that fCSQLDate function is culture-specific - i.e. it will parse the date based on the user's locale settings. That's why you see the problem.
Anyway, using queries with concatenated strings is always a bad idea (injection attacks). You are better off if you use parameters.
Access uses # as date field delimiter. The format should be #mm/dd/yyyy# probably the #mm-dd-yyyy# will also work fine.
Sorry I don't know mysql, but with oracle I would always explicity state the format that I was expecting the format to be in, eg: 'DD-MM-YYYY', to avoid (regional) date format problems
Why not use the format
dd mmm yyyy
There is only one way it can be interpreted.
You can use the Date() function to return a universal date based on the machine date and time settings. The region settings on the machine will determine how it it formatted on the client end. If you leave the field as strictle a DateTime field then the cleint region settings can format the date.
Going into the server, using the Date() function should aslo work (returning a universal date value).
Also, use a command object and parameters in your query when you pass them to avoid SQL injection attacks on string fields.

Resources