Comparing string with SmallDateTime used to work - sql-server-2008

I'm trying to debug an old VB6 program at my job. It's full of bugs and hardcoded stuff.
The program is connecting on a SQL Server 2005 database to read and write info using stored procedures.
Since the program is still being used while I'm working on it, I made a backup of the database to test some things and restored it in my version of SQL Server 2008. Everything was working fine.
When I came in the next morning, I got an error I didn't have the previous night even though the program wasn't used in the night.
The problem :
"exec dbo.sp_Get_Wait_Data '" & DateEx & "'"
DateEx is a string containing "2012/06/14"
The stored procedure :
[sp_Get_Wait_Data] #Datest as char(10)
AS
SELECT
(A lot of column names here)
FROM
Fiche
LEFT JOIN
voyage ON fcid = vofiche
LEFT JOIN
client on fcaccount = cusnov
WHERE
fcdate = #Datest
AND (void is null or (void > 0 and (void <> 999 and void <> 1000 and void <> 998)))
AND ((fcremarques NOT LIKE '%SYSANNULATION%' OR
fcremarques IS NULL)
AND fcrettime IS NOT NULL)
ORDER BY
FcTime, FcOrgSite, fcdessite
The error message :
The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value
So the error is here fcdate=#Datest in the stored procedure. I tried adding this line in the stored procedure
SELECT convert(datetime, #Datest, 120)
which worked like a charm for the convertion within the query but caused a few hundred other errors within the program when other queries tried to access this variable so it is not an option.
Any idea why this query was working perfectly yesterday and now it's giving me this error? Thanks in advance.

You probably have set dateformat dmy when connecting to the copy of your database. The date format is set implicitly by the language used. set language.
You could change the format of the parameter to YYYYMMDD which will be safe regardless of set dateformat or even better, change your parameter to datetime.
If that is not an option you can rewrite your query using where fcdate=convert(datetime, #Datest, 111)

Related

Delphi datatype for SQL Server last_user_update

The SQL Server code below returns the time-date of the last update to a table (any row.)
SELECT OBJECT_NAME(OBJECT_ID) AS DatabaseName, last_user_update
FROM sys.dm_db_index_usage_stats
WHERE OBJECT_ID=OBJECT_ID('TableName')
AND (Index_ID = 1)
If I use this in a TFDQuery, what is the datatype FDQuery1.FieldByName('last_user_update')?
If I want to store and compare this value at different times in a Delphi variable, what Delphi datatype should I assign it to, Double?
You use a TDateTime for this.
Although the TDateTime is represented internally by a double you don't use a double because you'll miss out on all the date/time support.
The code goes like this.
var
LastUpdate: TDateTime;
begin
//Do query etc.
...
LastUpdate:= MyQuery.FieldByName('last_user_update').AsDateTime;
Note that SQL server 7 and before do not have support for TDate. So if you just want the date part this code will fail in SQL server 7.
LastUpdate:= MyQuery.FieldByName('last_user_update').AsDate;
Just get the full DateTime and strip of the Time part later.
However, you're working with 2008 so just extracting the date will work fine for you.
Here's a list of DateTime functions: http://www.delphibasics.co.uk/ByFunction.asp?Main=DatesAndTimes

VBA code doesn't work if mysql table has unsigned values

I wrote the vba code below:
For x = 1 To Anno.Options.Length
If Anno.Options(x).Text = CStr(LU(2, CL)) Then
Anno.selectedIndex = x
Exit For
End If
Next x
It takes the values of "LU(2, CL)" (from a query in mySql) and uses it to find the option to activate.
Usually it works, but if I set the values ​​as "unsigned" in the database, no longer works and I get the error: " Variable uses an Automation type not supported in Visual Basic " (This is a translation of the error message in Italian)
Here's my question:
Is there a way to use "unsigned" type with excel?
Edit (clarifications):
LU is an array (type variant) that takes values with: LU = rs.getrows (where rs is a recordset resulted from a query on mySql)
If I modify the MySql database table by setting the field as "unsigned" (I'm talking about one of the fields acquired in LU by the query in the vba code) I get the error.

Could this simple T-SQL update fail when running on multiple processors?

Assuming that all values of MBR_DTH_DT evaluate to a Date data type other than the value '00000000', could the following UPDATE SQL fail when running on multiple processors if the CAST were performed before the filter by racing threads?
UPDATE a
SET a.[MBR_DTH_DT] = cast(a.[MBR_DTH_DT] as date)
FROM [IPDP_MEMBER_DEMOGRAPHIC_DECBR] a
WHERE a.[MBR_DTH_DT] <> '00000000'
I am trying to find the source of the following error
Error: 2014-01-30 04:42:47.67
Code: 0xC002F210
Source: Execute csp_load_ipdp_member_demographic Execute SQL Task
Description: Executing the query "exec dbo.csp_load_ipdp_member_demographic" failed with the following error: "Conversion failed when converting date and/or time from character string.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
End Error
It could be another UPDATE or INSERT query, but the otehrs in question appear to have data that is proeprly typed from what I see,, so I am left onbly with the above.
No, it simply sounds like you have bad data in the MBR_DTH_DT column, which is VARCHAR but should be a date (once you clean out the bad data).
You can identify those rows using:
SELECT MBR_DTH_DT
FROM dbo.IPDP_MEMBER_DEMOGRAPHIC_DECBR
WHERE ISDATE(MBR_DTH_DT) = 0;
Now, you may only get rows that happen to match the where clause you're using to filter (e.g. MBR_DTH_DT = '00000000').
This has nothing to do with multiple processors, race conditions, etc. It's just that SQL Server can try to perform the cast before it applies the filter.
Randy suggests adding an additional clause, but this is not enough, because the CAST can still happen before any/all filters. You usually work around this by something like this (though it makes absolutely no sense in your case, when everything is the same column):
UPDATE dbo.IPDP_MEMBER_DEMOGRAPHIC_DECBR
SET MBR_DTH_DT = CASE
WHEN ISDATE(MBR_DTH_DT) = 1 THEN CAST(MBR_DTH_DT AS DATE)
ELSE MBR_DTH_DT END
WHERE MBR_DTH_DT <> '00000000';
(I'm not sure why in the question you're using UPDATE alias FROM table AS alias syntax; with a single-table update, this only serves to make the syntax more convoluted.)
However, in this case, this does you absolutely no good; since the target column is a string, you're just trying to convert a string to a date and back to a string again.
The real solution: stop using strings to store dates, and stop using token strings like '00000000' to denote that a date isn't available. Either use a dimension table for your dates or just live with NULL already.
Not likely. Even with multiple processors, there is no guarantee the query will processed in parallel.
Why not try something like this, assuming you're using SQL Server 2012. Even if you're not, you could write a UDF to validate a date like this.
UPDATE a
SET a.[MBR_DTH_DT] = cast(a.[MBR_DTH_DT] as date)
FROM [IPDP_MEMBER_DEMOGRAPHIC_DECBR] a
WHERE a.[MBR_DTH_DT] <> '00000000' And IsDate(MBR_DTH_DT) = 1
Most likely you have bad data are are not aware of it.
Whoops, just checked. IsDate has been available since SQL 2005. So try using it.

When querying a MySql DB VBScript is returning asian characters instead of English

I am using VBScript to query a MySQL database that contains only English characters. The query is basically: SELECT * FROM table name PROCEDURE ANALYSE(1,1)
When I run the query directly on the DB it returns the expected results. However, when the query is run through VBScript it returns gibberish (Chinese?). I know for a fact the DB only contains English as I am the one who built it. I've run numerous other queries against the same table and haven't had any problems. Its only when I run the PROCEDURE ANALYSE query that it returns something unexpected.
The VBScript code is as follows:
strSQLcommand = "SELECT * FROM " & strTempTableName & " PROCEDURE ANALYSE(1,1)"
otRecordset.Open strSQLcommand,Connection
If Not otRecordset.EOF Then
otRecordset.movefirst
Do While NOT otRecordset.EOF
wscript.echo otRecordset(0).value
wscript.echo otRecordset(1).value
otRecordset.Movenext
Loop
End If
I've never had a problem with returning values from any other table in this DB. I've run this query numerous times and always get the same results which has me perplexed.
Any thoughts or ideas are greatly appreciated!
Ok, so, it turns out it has nothing to do with the DB per se.
I decided to start checking the data types that were being returned using the VBScript VarTYpe() method. The fields that were returning "gibberish/Chinese" had a data type of 8092. Basically, a byte array. Sprinkling a little Google fairy dust led me to this function:
Function C8209toStr(body8209)
If VarType(body8209) = 8209 Then
Dim i
ReDim aOut(UBound(body8209))
For i = 1 to UBound(body8209) + 1
aOut(i-1) = chr(ascb(midb(body8209,i,1)))
Next
C8209toStr = Join(aOut, "")
End If
End Function
Hope that helps whoever else comes along!

MySQL - Passing UTC timestamps to sprocs via JDBC

I have a MySQL Server set to UTC (##global.time_zone = '+00:00') and a table with a DATETIME column in which I store dates in UTC. I'm having problems getting UTC dates to come through when I call a stored procedure via JDBC. Example:
java.util.Date now = new java.util.Date();
sproc = conn.prepareCall("{call TzTestInsert(?)}");
sproc.setTimestamp(1, new java.sql.Timestamp(now.getTime()), Calendar.getInstance(TimeZone.getTimeZone("GMT+00:00")));
sproc.execute();
The TzTestInsert sproc simply takes a DATETIME and inserts it into the table.
I'd expect the database to now hold my current time in UTC, but in fact it holds the current time for my timezone.
If I change the sproc to take a string it works...
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
...
sproc.setString(1, dateFormat.format(now));
but I'd rather use the correct type in the sproc.
Also works if I bypass the sproc, but again not my preferred solution...
String sql = "INSERT INTO TzTest VALUES('" + dateFormat.format(now) + "') ;
With the original sproc I have the same issue if I use a TIMESTAMP datatype in the sproc and table, which isn't surprising with the server in UTC since any timezone conversions specific to MySQL TIMESTAMP should be noops.
Calling the sproc from a MySQL Workbench connection works fine, e.g.
CALL TzTestInsert(UTC_TIMESTAMP());
Seems like the problem is in JDBC. I've looked at the various timezone connection parameters and haven't found any that make a difference.
I must be missing something basic - lots of people do this, right?
Solution was to pass the JDBC driver "useLegacyDatetimeCode=false". See mysql bug http://bugs.mysql.com/bug.php?id=15604
Looks like they left the old code in the driver for backwards compatibility.