I have a tables that look something like this
Table1
Source OriginalCreatedDate
[email protected] 2022-12-24 06:01:25.000
[email protected]
Table 2
Source CreatedDate
[email protected] 2022-12-24 06:01:25.000
[email protected] 2023-08-07 02:01:25.000
I'm just wondering how can I update Table 1 OriginalCreatedDate column using Table2 CreatedDate column.
I believe I'll need to use the Source column to compare both tables but I'm just wondering how can I update Table1 rows that have null or '' value only. I want to ignore a row that already have OriginalCreatedDate value.
UPDATE Table1
SET Original_CreatedDate = ISNULL((
SELECT Top 1 Table2.CreatedDate
FROM Table2
WHERE Table2.Source = Table1.Source
), Table1.Original_CreatedDate)
GO
Any help or suggestion would be really appreciated
2条答案
按热度按时间gzjq41n41#
mwecs4sa2#
Really, you should not be using
varchar
for either of these columns. You're getting formatting differences because you're storing strings when you shouldn't have to worry about format at all because date/time values are not strings.To deal with your current scenario, where the source or the target can be NULL, an empty string, any number of spaces, or junk, I would do it this way:
Example
But really you should fix those columns so they're the right data type in the first place, or at least protect them with constraints so junk gets rejected. If both columns were
datetime
, the solution would be much simpler.