简体   繁体   English

SQL Server:NVARCHAR列以存储日期

[英]SQL Server : NVARCHAR column to store date

I have a query that needs to be output in CSV. 我有一个查询,需要以CSV输出。

No problem I say, but then this happens: 我说没问题,但是然后发生了:

There are two columns (from and to date) which are date type, but I am trying to store them as nvarchar or varchar (tried both). 有两列(从日期到日期)是日期类型,但是我试图将它们存储为nvarcharvarchar (都尝试了)。 This is in order to be able to insert the column headers in the extract. 这是为了能够在提取中插入列标题。

I have tried a couple of CONVERT , CAST , STUFF to force the date in the format of YYYY-MM-DD , but to no avail. 我尝试了几个CONVERTCASTSTUFFYYYY-MM-DD的格式强制日期,但无济于事。

Currently it is in this format: Jan 1 2014 12:00AM 当前采用这种格式: Jan 1 2014 12:00AM

I have tried almost everything I've found on Stack Overflow in similar topics, but nothing has worked for me. 我已经尝试了在类似主题的Stack Overflow上找到的几乎所有内容,但没有任何结果适合我。

I would also be happy if there could be an alternative on the column names, as I have not experimented with that one a lot. 如果列名上可以有其他选择,我也很高兴,因为我还没有尝试过很多。

Currently this is being used: 当前正在使用:

SELECT 'Column1', 'Column2', 'Column3'
UNION ALL
SELECT * FROM [Database].[dbo].Table

I think you want convert(varchar(10), col, 120) which will truncate a date format of yyyy-mm-dd hh:mi:ss(24h) to yyyy-mm-dd 我认为您想要convert(varchar(10), col, 120)这将截断yyyy-mm-dd hh:mi:ss(24h)的日期格式为yyyy-mm-dd

see cast and convert for more details 有关更多详细信息,请参见演员表和转换

SELECT 
     'id'          AS id
     , 'date_from' AS date_from
     , 'date_to'   AS date_to
UNION ALL
SELECT 
     convert(varchar(10), id)
     , convert(varchar(10), date_from, 120)
     , convert(varchar(10), date_to, 120) 
FROM [Database].[dbo].Table

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM