Type Clash when using Datediff(...Dateadd(...),Getdate()) in Sybase - sql

I've switched companies and in doing so, switched from SQL Server to Sybase-ASE. I can't tell if I'm just having a brain fart and am coding incorrectly or if there is a difference between running Datediff(...Dateadd(...),Getdate()) in SQL Server and Sybase-ASE. I'm getting a type clash (INT) on the Datediff side of the formula when running the code below. Running Dateadd by itself works fine. Not sure if something needs to be tweaked or it just can't be done in Sybase-ASE. Any help? I checked these other questions but no real help (Subtract one day from datetime GETDATE last month Get the records of last month in SQL server Datediff GETDATE Add)
SELECT TOP 5 *
FROM SalesData fm
WHERE fm.Date = DATEDIFF(MONTH, DATEADD(MONTH,-1,MAX(fm.Date)),GETDATE())
ALSO, side question: I can't remember what the specific formula is to get the whole of last month is in Datediff if anyone happens to know. I can figure it out I just figured it's best to kill two birds with one stone. It's apparently somewhat difficult to get a Dates table implemented into production...

On the point of built-in functions, ASE and SQLServer are nearly identical. There is however one difference, and this is what you may be hitting. In SQLServer, you can use a numeric value for a date, which is interpreted in SQLServer as #days since 01-01-1900. ASE does not support using numeric values as a date, and you will get a syntax error.

Nevermind, I got it thanks to this post(Get the records of last month in SQL server)
where DATEPART(MONTH,fm.Date) = DATEPART(MONTH, DATEADD(MONTH,-1,GETDATE()))
AND DATEPART(YEAR,fm.Date) = DATEPART(YEAR, DATEADD(YEAR,0,GETDATE()))

Related

SQL Server : best practice query for date manipulation

Long time listener, first time caller.
At work we have all of the date columns for most tables stored in as a simple "string" (varchar) formats. Such as yyyymmdd (eg. 20220625) or yyyymm (202206) etc.
Now for a lot of queries that are time based we need to compare to current date, or some fixed offset from current date.
Now two obvious versions that I know of to get current utc date into either of those formats are the following (for yyyymm as example):
SELECT LEFT(CONVERT(VARCHAR, GETUTCDATE(), 112), 6) ...
SELECT CONVERT(VARCHAR(6), GETUTCDATE(), 112) ...
I'm wondering if anyone knows of a better way, either both idiomatically or performance wise to convert those, and/or is there anything wrong with the second one to be worried about versus the first one in regards to either security/reliability etc? The second one definitely satisfies my code golf sensibilities, but not if it's at the expense of something I'm unaware of.
Also for some extra context the majority of our code runs in SQL Server or T-SQL, BUT we also need to attempt to be as platform agnostic as possible as there are customers on Oracle and/or Mysql.
Any insight/help would be highly appreciated.
There is no problem with either approach. Both work just fine. It is a matter of personal preference which to choose. The first looks more explicit, the second is shorter and thus easier to read maybe. As to performance: You want to get the current day or month only once in a query, so the call doesn't realy affect query runtime.
As to getting this platform agnostic is quite a different story. SQL dialects differ. Especially when it comes to date/time handling. You already notice that SQL Server's date functions are quite restricted. In Oracle and MySQL you would simple state the format you want (TO_CHAR(SYSDATE, 'YYYYMM') in Oracle and DATE_FORMAT(CURRENT_DATE, '%Y%m') in MySQL). But you also see that the function calls differ.
Now, you could write a user defined function GET_CURRENT_MONTH_FORMATTED for this which would return the string for the current month, e.g. '202206'. Then you'd have the different codes hidden in that function and the SQL queries would all look the same. The problem, though, is how to tell the DBMS that the function result is deterministic for a particular timestamp? If you run the query on December 31, 2022 at 23:50 and it runs until January 1, 2023 at 0:20, you want the DBMS to call this function only once for the query resulting in '202212' and not being called again, suddenly resulting in another string '202301'. I don't even know whether this is possible. I guess it is not.
I think you cannot write a query that does what you want and looks the same in all mentioned DBMS.

Where in my query to place the CONVERT to convert DateTime to Date

Just learning SQL and I've searched many options about converting a DateTime into a Date, and I do not want current date. It's a super simple query from this website: https://sqlzoo.net/wiki/Guest_House_Assessment_Easy
SELECT booking_date, nights
FROM booking
WHERE guest_id=1183
But the output is with the timestamp and I just want the date. I've searched so many forums and tried all their suggestions, including this:
SELECT CONVERT(varchar(10), <col>, 101)
So I've done:
SELECT CONVERT(varchar(10), booking_date,101), nights
FROM booking
WHERE guest_id=1183
But I'm getting syntax errors. This is probably so simple and you'll all think me an idiot, but I'd greatly appreciate help. It's driving me nuts.
When I fiddled about at your sqlzoo link I got the error
execute command denied to user 'scott'#'localhost' for routine 'gisq.to_date'`.
When I googled gisq.to_date I got this link https://sqlzoo.net/wiki/Format_a_date_and_time
Which has examples of how this dialect represents dates. See if you can work it out. Something like this:
SELECT date_format(booking_date,'%d/%m/%Y')
FROM booking
You didn't post the error in your question which is a big mistake. When you get an error message, you actually have something to work from.
It is also very important to note that the query above returns a string, not a date. It's only good for display, not for date arithmetic
TBH that seems like a terrible site to learn on as it gives no clues about the dialect. it looks like Oracle but to_date and trunc don't work.
The use of convert() suggests that you think you are uinsg SQL Server. If you only want the date component of a date/time data type, then you can use:
SELECT CONVERT(DATE, booking_date), nights
FROM booking
WHERE guest_id = 1183;
The syntax error suggests that you are not using SQL Server.
CONVERT() is bespoke syntax for SQL Server. Examples of similar functionality in other databases are:
DATE(booking_date)
TRUNC(booking_date)
DATE_TRUNC('day', booking_date)
In addition, what you see also depends on the user-interface.
In your case, the data is being stored as a date with no time component, but the UI is showing the time. For that, you want to convert to a string. That site uses MariaDB -- which is really a flavor of MySQL-- and you would use:
DATE_FORMAT(booking_date, '%Y-%m-%d')

Subtract hours from SQL Server 2012 query result

I am running queries on an alarm system signal automation platform database in SQL Server 2012 Management Studio, and I am running into some hiccups.
My queries run just fine, but I am unable to refine my results to the level that I would like.
I am selecting some columns that are formatted as DATETIME, and I simply want to take the value in the column and subtract 4 hours from it (i.e., from GMT to EST) and then output that value into the query results.
All of the documentation I can find regarding DATESUB() or similar commands are showing examples with a specific DATETIME in the syntax, and I don't have anything specific, just 138,000 rows with columns I want to adjust time zones for.
Am I missing something big or will I just need to continue to adjust manually after I being manipulating my query result? Also, in case it makes a difference, I have a read-only access level, and am not interested in altering table data in any way.
Well, for starters, you need to know that you aren't restricted to use functions only on static values, you can use them on columns.
It seems that what you want is simply:
SELECT DATEADD(HOUR,-4,YourColumnWithDateTimes)
FROM dbo.YourTable
Maybe it will be helpful
SELECT DATEPART(HOUR, GETDATE());
DATEPART docs from MSDN

oracle sql developer(4.0.0.12) returns wrong date

It seems that a query of mine returns wrong results, and I'm not sure why. I don't yet rule out the possibility that the SQL is actually doing something else then what I expect/want it to do since I haven't used SQL for a time now.
I post it here because I'm kind a stuck with the why it returns wrong results sometimes.
The error is in the MIN(FIRM.account_recharge.X__INSDATE) (or at least the ones I noticed)
SELECT
FIRM.customer.CUSTOMER_ID,
FIRM.customer.CORPORATION,
FIRM.customer.CUSTOMER_NAME_PREFIX,
FIRM.customer.CUSTOMER_NAME,
FIRM.account.ACCOUNT_TYPE,
FIRM.account.ACCOUNT_TYPE,
FIRM.customer.LANGUAGE,
FIRM.customer.VALIDATED,
FIRM.account.X__INSDATE,
SUM(FIRM.account_recharge.GROSS_VALUE) SUM_FELTOLTESEK,
MIN(FIRM.account_recharge.X__INSDATE),
INNER JOIN FIRM.account
ON FIRM.customer.CUSTOMER_ID = FIRM.account.CUSTOMER
INNER JOIN FIRM.customer_address
ON FIRM.account.CUSTOMER = FIRM.customer_address.CUSTOMER
INNER JOIN FIRM.account_recharge
ON FIRM.account.ACCOUNT_ID = FIRM.account_recharge.ACCOUNT
GROUP BY FIRM.customer.CUSTOMER_ID,
FIRM.account.X_INSDATE,
FIRM.customer.CORPORATION,
etc,etc
HAVING MIN(FIRM.account_recharge.X__INSDATE) BETWEEN to_date('2014-JAN. -01','YYYY-MON-DD') AND to_date('2014-DEC. -31', 'YYYY-MON-DD');
This code should return information abut our customers, their sum account 'recharging'/'replenishing'/'paying in' , sorry not sure of what word to use here. and their first payment/money upload to their account in 2014. Yet sometimes the return values seems to just ignore the actual first time our client paid in money, and shows the second or third date. (my random manual check returned that around 1/10 of the time the returned values are wrong.)
A costumer of ours can have more the one account linked to him. I'm using Oracle SQL developer (4.0.0.12) please ask if you would like to know anything else about this pickle im in.
Otherwise It seems to work nicely, but if you have any other tuning tip, I would be glad to hear them.
Thank you for your help!
HAVING MIN(FIRM.account_recharge.X_INSDATE) BETWEEN '14-JAN. -01' AND '14-DEC. -31'
This is definitely incorrect. You are comparing dates. so, you must convert the string literal explicitly into a date using TO_DATE and proper format mask.
For example,
HAVING MIN(FIRM.account_recharge.X_INSDATE)
BETWEEN to_date('2014-JAN-01','YYYY-MON-DD')
AND to_date('2014-DEC-31', 'YYYY-MON-DD')
Also, do not use YY to denote the year. You don't have to re-invent the Y2K bug again. Always use YYYY format for an year. Else, if you are stuck with YY values for year, then use RR format. But, I would insist, always use YYYY format for year.

DATEDIFF command won't work as 'day' is not a recognised column

I'm relatively new to SQL and have been attempting to run a script wherein I can bring up the number of days that have passed between two points in time. I understand how this should look based on your website, but for some reason when I input the values, my database is returning the following error:
ProgrammingError: ERROR: column "day" does not exist
The code I'm using is:
select datediff(day, '2014-01-01', '2014-02-01')
I assume I'm missing something very simple (this is a hugely basic query I'm sure), but would be appreciative of any assistance. I've variously tried pointing it towards the specific table I want to draw from, but it keeps stumbling on this error.
If you are doing this in postgresql then use
select DATE_PART('day', '2014-01-01'::timestamp - '2014-02-01'::timestamp)