Issue
My dataset that I am using to create my SQL database has datapoints that are formatted as YYYY-MM, but as far as I have found there isn't a format for SQL in order to store that specifically. I am using Python and pyodbc to create a script that builds this database and updates it.
Is there any solution for this datatype within SQL that I am missing, or perhaps some way to solve this problem using the tools available in Pandas or something in Python?
Solution
If you can't fix the python source to output a date instead of part of a date, we can handle this a different way.
Let's say your real table looks like this:
CREATE TABLE dbo.PythonInput
(
SomeKey int CONSTRAINT PK_pi PRIMARY KEY,
EventDate date
);
Create a staging table that mimics it, except that the date column is actually a string:
CREATE TABLE dbo.Staging_PythonInput
(
SomeKey int CONSTRAINT PK_st_pi PRIMARY KEY,
EventDate char(7)
);
Now you can have a trigger that just moves the data to your real table after massaging the date column:
CREATE TRIGGER dbo.CorrectBadPythonInput
ON dbo.Staging_PythonInput
INSTEAD OF INSERT
AS
INSERT dbo.PythonInput
(
SomeKey,
EventDate
)
SELECT
i.SomeKey,
TRY_CONVERT(date, i.EventDate + '-01', 120)
FROM inserted AS i;
Then tell Python to insert into your staging table instead, e.g.:
INSERT dbo.Staging_PythonInput(SomeKey, EventDate)
VALUES(1, '2022-07'), (2, '2022-03'),
(3, '2019-05'), (4, '0123-67');
Now a query against the source table:
SELECT SomeKey, EventDate FROM dbo.PythonInput;
Yields:
| SomeKey | EventDate |
|---|---|
| 1 | 2022-07-01 |
| 2 | 2022-03-01 |
| 3 | 2019-05-01 |
| 4 | null |
- Example db<>fiddle
If you want to prevent the row with the invalid date from getting in, you can just add this to the trigger:
WHERE TRY_CONVERT(date, i.EventDate + '-01', 120) IS NOT NULL;
(And then you could run a different insert into a logging table if you want to track rows that were rejected.)
Answered By - Aaron Bertrand Answer Checked By - Timothy Miller (sql.easybugfix Admin)
Post a Comment
Post a Comment