You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL新手求助:如何将DocumentDate字段拆分为DATE和TIME两个新字段

Hey there! Since you're new to SQL, let's break this down step by step—splitting a DocumentDate datetime field into separate date and time columns is a super common task, and the exact code depends on which SQL database you're working with. Below are the most common scenarios to get you sorted:

SQL Server (matches your example datetime format)

First, you'll need to add the two new columns to your table:

ALTER TABLE YourTableName 
ADD DATE DATE, TIME TIME;

Then populate them by converting the original DocumentDate field:

UPDATE YourTableName 
SET DATE = CAST(DocumentDate AS DATE),
    TIME = CAST(DocumentDate AS TIME);

If you want these columns to automatically stay in sync with DocumentDate (no manual updates later), you can use persisted computed columns instead:

ALTER TABLE YourTableName 
ADD DATE AS CAST(DocumentDate AS DATE) PERSISTED,
    TIME AS CAST(DocumentDate AS TIME) PERSISTED;
MySQL

Adding the columns is similar, but we use built-in date/time functions to extract the values:

ALTER TABLE YourTableName 
ADD DATE DATE, TIME TIME;

Then update the data:

UPDATE YourTableName 
SET DATE = DATE(DocumentDate),
    TIME = TIME(DocumentDate);
PostgreSQL

Note: DATE and TIME are reserved keywords in PostgreSQL, so we'll wrap them in double quotes to avoid errors:

ALTER TABLE YourTableName 
ADD "DATE" DATE, "TIME" TIME;

Then populate the columns using PostgreSQL's type casting syntax:

UPDATE YourTableName 
SET "DATE" = DocumentDate::DATE,
    "TIME" = DocumentDate::TIME;

Quick Tip

Always make sure to replace YourTableName with the actual name of your table. If you're working with a different database (like Oracle or SQLite), feel free to mention it and I can share the specific code for that system.

内容的提问来源于stack exchange,提问作者Stephen oxley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 22:03:14