SQL Computed Column , Coallesce , Two DateTime Fields , Index - sql

I have in my database following two Columns :
Delivery_Date (DateTime)
Delivery_Override (DateTime)
( I must preserve the Original Delivery Date for other things I do )
I created following Computed Column
Delivery_Packdate
formula : (coalesce(nullif([Delivery_Override],''),[Delivery_Date]))
and now I can do a select like this :
select * from Deliveries where Delivery_PackDate = '2019-09-24'
and this automatically selects the Overriden Date if filled or else the original date.
the Problem is I would like to index this , but SQL will not allow this because it is non-deterministic .
I suppose I am doing something wrong here , how can I solve this correctly ? Any tips?
Thank you.

The problem is that you are converting to a string. The following works fine:
create table t (
Delivery_Override datetime,
Delivery_Date datetime
);
alter table t add dt as (coalesce(Delivery_Override, Delivery_Date)) persisted;
create index idx_t_dt on t(dt);
Here is a db<>fiddle.
There is no such thing as a date/time with the value ''.

Related

SQL Server - Looking for a way to shorten code

I'm basically very new to SQL Server, so please bare with me. Here is my problem:
I have a table with (let's say) 10 columns and 80k rows. I have 1 column called Date in the format of YYYY-MM-DD type varchar(50) (can't convert it to date or datetime type I tried, the initial source of data is not good).
**Example :
Table [dbo].[TestDates]
Code
SellDate
XS4158
2019-11-26
DE7845
2020-02-06
What I need to do is to turn the YYYY-MM-DD format to DD/MM/YYYY format. After a lot of tries (I tried the functions (DATE_FORMAT, CONVERT, TO_DATE etc) and this is solution :
1- I added a primary key for join purpose later (ID)
2- I split my date column in 3 columns in a whole new table
3- I merged the 3 columns in the order I need with the delimiter of my choice (/) in the same new table
4- I copied the good column to my initial table using the primary key ID I created before
alter table [dbo].[TestDates]
add ID int not null IDENTITY primary key;
SELECT ID,
FORMAT(DATEPART(month, [SellDate]),'00') AS Month,
FORMAT(DATEPART(day, [SellDate]),'00') AS Day,
FORMAT(DATEPART(year, [SellDate]),'0000') AS Year
INTO [dbo].[TestDates_SPLIT]
FROM [dbo].[TestDates]
GO
ALTER TABLE [dbo].[TestDates_SPLIT]
ADD SellDate_OK varchar(50)
UPDATE [dbo].[TestDates_SPLIT]
SET SellDate_OK = [Day] + '/' + [Month] + '/' + [Year]
ALTER TABLE [dbo].[TestDates_SPLIT]
DROP COLUMN Month, Day, Year
ALTER TABLE [dbo].[TestDates]
ADD SellDate_GOOD varchar(50)
UPDATE [dbo].[TestDates]
SET [TestDates].SellDate_GOOD = [TestDates_SPLIT].SellDate_OK
FROM [dbo].[TestDates]
INNER JOIN [dbo].[TestDates_SPLIT]
ON [TestDates].ID = [TestDates_SPLIT].ID
This code works but i find too heavy and long, considering I have 6 more dates columns to work on. Is there a way to make it shorter or more efficient? Maybe with SET SellDate = SELECT (some query of sorts that doesn't require to create and delete table)
Thank you for your help
I tried the usual SQL functions but since my column is a varchar type, the converting was impossible
You should not be storing dates as text. But, that being said, we can try doing a rountrip conversion from text YYYY-MM-DD to date to text DD/MM/YYYY:
WITH cte AS (
SELECT '2022-11-08' AS dt
)
SELECT dt, -- 2022-11-08
CONVERT(varchar(10), CONVERT(datetime, dt, 121), 103) -- 08/11/2022
FROM cte;
Demo

Display Now date and Time in SQl table column

I want to be able to have todays date and time now in a table column
If my table is say Table1, basically it should display the time and date when
SELECT * FROM Table1 is run.
I've tried the following but they just show the time from the moment in time I assign the value to column
ALTER TABLE Table1
ADD TodaysDate DateTime NOT NULL DEFAULT GETDATE()
and
ALTER TABLE Table1
ADD TodaysDate DateTime
UPDATE Table1
SET TodaysDate = GETDATE()
Hope this is clear. any help is appreciated.
Thanks
In SQL Server you can use a computed column:
alter table table1 add TodaysDate as (cast(getdate() as date));
(use just getdate() for the date and time)
This adds a "virtual" column that gets calculated every time it is referenced. The use of such a thing is unclear. Well, I could imagine that if you are exporting the data to a file or another application, then it could have some use for this to be built-in.
I hope this clarifies your requirement.
The SQL Server columns with default values stores the values inside the table. When you select the values from table, the stored date time will be displayed.
There are 2 options I see without adding the column to the table itself.
You can use SELECT *, GETDATE() as TodaysDate FROM Table1
You can create a view on top of Table 1 with additional column like
CREATE VIEW vw_Table1
AS
SELECT *, GETDATE() as TodaysDate FROM dbo.Table1
then you can query the view like you mentioned (without column list)
SELECT * FROM vw_Table1
This will give you the date and time from the moment of the execution of the query.

Order by on Two Datetime Fields .If one field is Null How to avoid Sybase from populating it with default datetime

I am using a Select Query to insert data into a Temp Table .In the Select Query I am doing order by on two columns something like this
insert into #temp
Select accnt_no,acct_name, start_date,end_date From table
Order by start_date DESC,end_date DESC
Select * from #temp
Here when there is an entry present in start_date field and an Null entry in the end_date field .During the order by operation Sybase is filling it with an Default date ( jan 1 1900 ) . I dont want that to happen .If the end_date field is Null . The data should be written just as Null .Any suggestion on how to keep it as Null even while fetching the data from the table .
The 1/1/1900 usually comes from trying to cast an empty string into a datetime.
Is your 'date' source column an actual datetime datatype or a string-ish varchar or char?
Sounds like the table definition requires that end_date not be null, and has default values inserted automatically to prevent them. Are you sure there are even nulls when you do a straight select on the table without the confusion of ordering and inserting?
I created a temp table with a nullable datetime column that has a default value.
Defaults are not there to handle nulls per se, they are there to handle missing values on inserts that were not supplied. If I run an insert without a column list (just as you have done) the default value does not apply and a null is still inserted.
I suggest adding the column list to your insert statement. This might prevent the problem (or expose a different problem in having them in the wrong order.)
insert into #temp (accnt_no, accnt_name, start_date, end_date)
select accnt_no,acct_name, start_date,end_date from ...
Here's a query that should help you find the actual defaults on any of the columns if you don't have access to the create script:
select c.name, object_name(cdefault), text
from tempdb..syscolumns c, tempdb..syscomments cm
where c.id = object_id('tempdb..#temp') and cm.id = c.cdefault

Sql order by date doesn't work in sqlite

I have this syntax SQL below:
SELECT * FROM products_validity WHERE type = 'milk' order by date sac
My row called 'date' is 'DATETIME' and records that are saved within this line follow this format:
day / month / year
And I'm having a problem, in my case he is adjusting according to the 'day', instead of doing a complete analysis of data, eg:
09/09/1234
10/10/2016
20/09/2014
23/08/2014
How to fix this error, causing the sql can order the correct way?
EDIT
My Table is in this format:
CREATE TABLE IF NOT EXISTS products_validity
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
product VARCHAR,
type VARCHAR,
date DATETIME,
desc VARCHAR,
show VARCHER

How do I get the current date in SQL when entering data to a microsoft database?

I am using Microsoft SQL Server and SQL Server Management Studio.
I have a column called dateApplied which has a constraint like this:
[dateApplied] >= getDate()
When I enter a row the date is automatically added the row.
My problem is when I use the SELECT function, the dateApplied column is automatically changed to the current date and time in which the SELECT statement is called.
How do I prevent this from happening?
Thanks
Peter
I suppose you're using a computed column, like:
create table t1
(
id int
, date_col as getdate()
)
Try a default constraint instead:
create table t1
(
id int
, date_col datetime constraint DF_T1_DateCol default getdate() not null
)
A computed column is calculated whenever you run a query. A default constraint is only generated when the row is first inserted.