Sql server 2008 r2 游标中的日期格式查询
我正在执行此查询:Sql server 2008 r2 游标中的日期格式查询,sql-server-2008-r2,Sql Server 2008 R2,我正在执行此查询: select createdate from OITM_CLONE where ItemCode ='bk1109' and U_SLV ='f' 它给出的输出类似于“2013-05-04 02:28:34.000” 但是我想在变量中获取日期,所以我使用这个查询 declare @da as varchar (20) declare @d as varchar(max) set @d=(select createdate from OITM_CLONE where Item
select createdate from OITM_CLONE where ItemCode ='bk1109' and U_SLV ='f'
它给出的输出类似于“2013-05-04 02:28:34.000”
但是我想在变量中获取日期,所以我使用这个查询
declare @da as varchar (20)
declare @d as varchar(max)
set @d=(select createdate from OITM_CLONE where ItemCode ='bk1109' and U_SLV ='f')
select @d
但它的输出类似于“2013年5月4日凌晨2:28”
我需要这种输出格式“2013-05-04 02:28:34.000”如果您想要一种特定的格式(通常最好将日期时间数据保留为日期时间数据,并在其他地方进行格式化),您需要使用并准确地告诉它您希望如何执行格式化:
set @d=(select CONVERT(varchar(max),createdate,121) from OITM_CLONE where ItemCode ='bk1109' and U_SLV ='f')
其中,
121
是“ODBC规范(毫秒)”格式。如下所示,您可以简单地将@d声明为datetime以避免转换
if exists
(
select * from tempdb.dbo.sysobjects
where id = object_id(N'[tempdb].dbo.[#ThisTable]')
)
DROP TABLE #ThisTable
;
create table #ThisTable
(
ItemCode tinyint
,createdate datetime
)
;
INSERT INTO #ThisTable
(ItemCode,createdate)
VALUES
(1,'2013-05-04 02:28:34.000')
,(2,'2013-05-04 02:28:34.000')
;
declare @da as varchar (20) ;
declare @d as varchar(max) ;
declare @dt as datetime ;
set @d=(select createdate from #ThisTable where ItemCode = 1)
set @dt=(select createdate from #ThisTable where ItemCode = 2)
select * from #ThisTable ;
select @d ;
select @dt ;
选择@d;
2013年5月4日凌晨2:28
选择@dt;
2013-05-04 02:28:34.000