1

如何将格式日期插入dd-mm-yyyy数据类型列Date

尝试了以下但显示错误

INSERT INTO Profiles (first_name, last_name, email, phone, 
                      [city(hometown)], created_at, gender, 
                      referral_code,marital_status) 
VALUES ('anusha', 'pariti', 'anusha.pariti@gmail.com', '8105987404', 
        'Bangalore', '16-04-2015', 'F', '7L5FZW', 'Y'),
       ('Ashish', 'Singh', 'ashish.singh@gmail.com', '9876890463', 
        'Bangalore','23-05-2015', 'M', 'KF34MF', 'Y')

错误:

从字符串转换日期和/或时间时转换失败。

INSERT INTO Profiles (first_name, last_name, email, phone, 
                      [city(hometown)],created_at, gender, 
                      referral_code, marital_status) 
VALUES ('anusha', 'pariti', 'anusha.pariti@gmail.com', '8105987404', 
        'Bangalore', CAST('16-04-2015' AS DATE), 'F', '7L5FZW', 'Y'),
       ('Ashish', 'Singh', 'ashish.singh@gmail.com', '9876890463', 
        'Bangalore', CAST('23-05-2015' AS DATE), 'M', 'KF34MF', 'Y')

错误:

从字符串转换日期和/或时间时转换失败。

INSERT INTO Profiles (first_name, last_name, email, phone, 
                      [city(hometown)], created_at, gender,  
                      referral_code, marital_status) 
VALUES ('anusha', 'pariti', 'anusha.pariti@gmail.com', '8105987404', 
        'Bangalore', CONVERT(DATE, '16-04-2015'), 'F', '7L5FZW', 'Y'),
       ('Ashish', 'Singh', 'ashish.singh@gmail.com', '9876890463', 
        'Bangalore', CONVERT(DATE, '23-05-2015'), 'M', 'KF34MF', 'Y')

错误:

从字符串转换日期和/或时间时转换失败。

4

5 回答 5

2

尝试使用可接受的格式插入您的日期,例如使用20150416而不是'16-04-2015

INSERT INTO Profiles (first_name, last_name, email, phone, [city(hometown)],
    created_at, gender, referral_code,marital_status)
VALUES
    ('anusha', 'pariti', 'anusha.pariti@gmail.com', '8105987404', 'Bangalore',
     '20150416', 'F', '7L5FZW', 'Y'),
    ('Ashish', 'Singh', 'ashish.singh@gmail.com', '9876890463', 'Bangalore',
     '20150523', 'M', 'KF34MF', 'Y');

这将允许您将数据存储为created_at列内的日期。这绝对是存储日期信息的方式。如果您以后想以原始方式格式化created_at,您可以使用CONVERT,例如

SELECT
    CONVERT(varchar, created_at, 105) AS created_at
FROM Profiles;
于 2017-09-29T04:11:17.063 回答
1

SQL Server 中最安全的日期文字是 YYYYMMDD

例如 INSERT into ... Values ('20170523', ...

看来您已经习惯了 DD-MM-YYYY,如果您想使用该序列,则需要使用带有样式编号的转换。

转换(日期,'23-05-2017',120)

于 2017-09-29T04:30:22.680 回答
0

在 SQL Server 2012+ 中,您可以使用

Select try_convert(date, '16-04-2015', 105)

否则你必须正确格式化字符串

于 2017-09-29T04:11:31.500 回答
0

你试过YYYY-MM-DD格式吗?SQL 中的数据格式为 YYYY-MM-DD。

于 2017-09-29T04:42:44.373 回答
0

你可以试试这个。

dd-mm-yyyy是意大利语格式,样式代码是 105,这就是为什么你应该使用这个代码来转换它。

INSERT INTO Profiles (first_name, last_name, email, phone, 
                      [city(hometown)], created_at, gender,  
                      referral_code, marital_status) 
VALUES ('anusha', 'pariti', 'anusha.pariti@gmail.com', '8105987404', 
        'Bangalore', CONVERT(DATE, '16-04-2015',105), 'F', '7L5FZW', 'Y'),
       ('Ashish', 'Singh', 'ashish.singh@gmail.com', '9876890463', 
        'Bangalore', CONVERT(DATE, '23-05-2015',105), 'M', 'KF34MF', 'Y') 
于 2017-09-29T06:04:38.990 回答