Oracle where clause date selection does not work - database

Basically, my problem can be re-created using the following script in oracle db:
create table test
(
current_date date
);
insert into test(current_date) values( TO_DATE('2018-02-01', 'yyyy-MM-dd') );
insert into test(current_date) values( TO_DATE('2018-03-01', 'yyyy-MM-dd') );
insert into test(current_date) values( TO_DATE('2018-04-01', 'yyyy-MM-dd') );
--select data later than May
select * from test where current_date >= TO_DATE('2018-05-01', 'yyyy-MM-dd') ;
But all three date come out as result? Why? Did I do something wrong here?
2/1/2018 12:00:00 AM
3/1/2018 12:00:00 AM
4/1/2018 12:00:00 AM

It's because current_date is an Oracle built-in function, returning the current date (and time). The way Oracle namespaces work means the built-in reference trumps your column name.
One way to fix it would be to use a table alias in your query:
select * from test t
where t.current_date >= TO_DATE('2018-05-01', 'yyyy-MM-dd') ;
This tells Oracle you're referencing the column name not the built-in.
Obviously the better solution is to change your table so you don't have a column name which clashes with an Oracle built-in.

Related

SQL Server: combine date column and time column, insert into datetime column

I have a database with a date and a time stored separately in datetime columns (not my idea). I need to combine their values to put into another table with a datetime column. As simple as this seems, I just don't seem to be able to do it.
I can get my date value:
cast(sampledate as date) -- returns '2014-11-01'
And my date value:
cast(CollectionTime as time) -- returns '06:46:00.0000000'
I've tried a few different ways of putting them together that look OK.
For example:
concat(cast(sampledate as date) , ' ' , cast(CollectionTime as time)) -- returns '2014-11-05 08:14:00.0000000'
But when I try to insert this into a datetime column, or even just cast it as a datetime value, it doesn't work:
cast(concat(cast(sampledate as date) , ' ' , cast(CollectionTime as time)) as datetime)
-- I get the error 'Conversion failed when converting date and/or time from character string.'
This link warned me against using the FORMAT function, and I've been to some other sites that tell me what NOT to do, but I just can't seem to do this simple thing. Can anyone help? Thanks.
EDIT: Figured it out. This link solved it for older versions of SQL, but not current versions. However, it works fine if you cast to datetime2(0), not datetime.
As I commented above, here is an example where you can add the two datetimes together.
If either column is NOT datetime, simply convert that column to a datetime
Declare #YourTable table (sampledate datetime,CollectionTime datetime)
Insert Into #YourTable values
('2019-06-25 00:00:00','09:09:31')
Select *
,NewDateTime = sampleDate + CollectionTime
From #YourTable
Results
sampledate CollectionTime NewDateTime
2019-06-25 00:00:00.000 1900-01-01 09:09:31.000 2019-06-25 09:09:31.000

Clickhouse datetime comparison not working as expected

I am trying to compare the datetime, in clickhouse. But it's seems it's working in some wired way.
I have a column in my table which I want to compare with (now(),'UTC').
If the value of datetime in that column is less then the (now(),'UTC') Time than I wanna select data from that record.
I have created the table like
create table my_table (`mytime` DateTime, `data' [type]) ENGINE= engine
I want the queue like
Select data from my_table where mytime < toDateTime(now(), 'UTC')
Even if mytime > toDateTime(now(), 'UTC') it always considers mytime < toDateTime(now(), 'UTC')
It seems to me that something may up with the way you inserted data or your ClickHouse version has a bug.
The following example shows how to do what you are attempting in a way that works on my 19.15.4.10 server as expected to select only the earlier row. Note the select sleep() to ensure now() invocations are different.
drop table if exists my_table;
create table my_table (mytime DateTime, data String) engine = Memory;
insert into my_table values(now(), 'a');
select sleep(1);
insert into my_table values(toDateTime('2020-01-01 00:00:00', 'UTC'), 'b');
select * from my_table where mytime < now();
select * from my_table where mytime < toDateTime(now(), 'UTC');
On my server it does not matter whether you select now() or convert it. I also tried the way you originally defined the table and that works too. Hence the thought that something is up with your data.
The reason behind this issue was in clickhouse, it takes DateTime and DateTime('UTC') as different objects, therefore the comparison between them does not work as expected. Since I wanted to make the comparison with (now(),'UTC'), I have to change the type of
mytime as DateTime ('UTC').
I have to change the table as
create table my_table (`mytime` DateTime ('UTC'), `data' [type]) ENGINE= engine

How can I compare a DATE value with the result of GETDATE()

I am trying to grant and revoke server roles for user id picked from a table.
I am using the following query to insert a row from master table to another table whenever the expiry date approaches, however the command is not inserting any rows into the slave table.
Insert into tbl2(userid, role, startdate, expirydate)
Select userid, role, startdate, expirydate
from tbl1
where expirydate = Dateadd(day,0, getdate())
If I use <= or >= the above query is working but that is not helpful when we have multiple rows in tbl1.
It's because GETDATE() returns a DATETIME value, and you're likely comparing it to a DATE, so you're effectively comparing values like this:
SELECT GETDATE() AS DateTimeValue,
CAST(GETDATE() AS DATE) DateValue;
Output:
DateTimeValue DateValue
2017-10-04 10:34:35.023 2017-10-04
By default, a DATE will have a time set to midnight if comparing to a DATETIME, like: 2017-10-04 00:00:00.000.
These values aren't going to be equal with a time included, so use CAST or CONVERT to get a DATE without the time:
where expirydate = Dateadd(day,0, CAST(GETDATE() AS DATE))
Although, it looks like you don't need that Dateadd on the WHERE clause, so remove it unless this is edited / sample code. So maybe edit it to this:
where expirydate = CAST(GETDATE() AS DATE)
Reference
GETDATE (Transact-SQL)
Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.

Entity framework getting record by exact date and time

In entity framework I am querying a view and getting records which match a certain id and datetime. I want to get records which have an exact both date and time as effDate.
var deals = context.Table
.Where(d => d.DealID == DealId && d.EffectiveDate == effDate)
.ToList();
This is the view in database.
When the dealId is 2013-00188 and effDate is shown above 2017/03/08 09:55:39 the query does not return any record however if you look at the database you can see their is a record which matches both id and effDate. Even when I add the nano second to effDate it doesnt bring any record.
To top it of this query bring back records in sql 2012 and sql 2014 however sql 2016 it doesn't!
I have included the sql generated by entity framework as you can see the date is not in the correct format and inside by database the Effective date is stored as a datetime not a datetime2. I need to make sure the date has the correct format.
SELECT
[Extent1].[DealID] AS [DealID],
[Extent1].[Item] AS [Item],
[Extent1].[EffectiveDate] AS [EffectiveDate],
[Extent1].[ChargeID] AS [ChargeID],
[Extent1].[SegmentCost] AS [SegmentCost],
[Extent1].[CustomSolutionsCost] AS [CustomSolutionsCost],
[Extent1].[ItemChargeIndicator] AS [ItemChargeIndicator],
[Extent1].[LandOCost] AS [LandOCost],
[Extent1].[TreatRate] AS [TreatRate],
[Extent1].[SegmentGrossProfit] AS [SegmentGrossProfit],
[Extent1].[CustomerSpecificPrice] AS [CustomerSpecificPrice],
[Extent1].[MultipleCustSpecific] AS [MultipleCustSpecific],
[Extent1].[ListPrice] AS [ListPrice],
[Extent1].[DataSource] AS [DataSource],
[Extent1].[BOMKeyField] AS [BOMKeyField],
[Extent1].[ItemDescription] AS [ItemDescription],
[Extent1].[AdditiveType] AS [AdditiveType],
[Extent1].[AdditiveTypeDescription] AS [AdditiveTypeDescription],
[Extent1].[SpecificGravity] AS [SpecificGravity],
[Extent1].[BOMSource] AS [BOMSource],
[Extent1].[CostDate] AS [CostDate],
[Extent1].[CostSource] AS [CostSource],
[Extent1].[PriceDate] AS [PriceDate],
[Extent1].[PriceSource] AS [PriceSource],
[Extent1].[Vendor] AS [Vendor],
[Extent1].[CreatedBy] AS [CreatedBy],
[Extent1].[CreatedDate] AS [CreatedDate]
FROM [dbo].[vwDealBOM] AS [Extent1]
WHERE ([Extent1].[DealID] = #p__linq__0) AND ([Extent1].[EffectiveDate] = #p__linq__1)
-- p__linq__0: '2013-00188' (Type = AnsiString, Size = 8000)
-- p__linq__1: '08/03/2017 09:55:39' (Type = DateTime2)
Any suggestion will be great.
effDate and EffectiveDate millisecond values are not equal. effDate millisecond value is 0 but you are looking for a record with 607.

Automatic adding current time in SQL Server 2012

I have table with a column of datatype time(4).
When I'm inserting values into the table I need to auto insert just the current time with milliseconds (without date) into that column. I have tried with time stamp, date time... but without any success.
If you want to get the current time in SQL Server 2012, just use the CAST operator to achieve this:
SELECT
CAST(SYSDATETIME() AS TIME(4))
This will get the current date & time, and cast this to just the time, as you need it.
To achieve automatic entry of time values when a new row is added, you can use the above expression in a default constraint. For example:
DECLARE #T AS table
(
SomeValue integer NOT NULL,
TheTime time(4) NOT NULL
DEFAULT CAST(SYSDATETIME() AS time(4))
);
INSERT #T (SomeValue)
VALUES (1);
SELECT
SomeValue,
TheTime
FROM #T;
As far as I understand, this is what you may be looking for:
SELECT GETDATE() 'Today',
CONVERT(TIME(4),GETDATE()) 'time_only'
You could use the above conversion in your insert statement as following:
INSERT INTO TABLEA (
column1
,column2
,record_insert_time
)
VALUES (
value1
,value2
,CONVERT(TIME(4), GETDATE())
);

Resources