我想我在这里疯了。
我正在尝试在 SQL Server 2005 上做一个 SP,它需要一个日期,在另一个表中查找它并分配一个期间号和周号(用于财务日历目的)。
输出需要将日期保存为字符串,而不是日期时间。
如果没有时间,我根本无法获得显示的日期。
我尝试了几种方法:
select cast(floor(cast(@CalcDate as float)) as datetime)
我制作了一个函数,将其转换为字符串并再次将其放回:
CREATE FUNCTION dbo.DateToVarchar (@DateIn datetime)
RETURNS varchar(10)
AS
BEGIN
declare @DD [varchar] (2)
declare @MM [varchar] (2)
declare @YYYY [varchar] (4)
declare @DateOut [varchar] (10)
declare @DDLen [int]
declare @MMLen [int]
set @DD = datepart(dd,@DateIn)
set @DDLen = len(@DD)
set @DD = (case when @DDLen < 2 then '0' + @DD else @DD end)
set @MM = datepart(mm,@DateIn)
set @MMLen = len(@MM)
set @MM = (case when @MMLen < 2 then '0' + @MM else @MM end)
set @YYYY = datepart(yyyy,@DateIn)
set @DateOut = @YYYY + '-' + @MM + '-' + @DD
return @DateOut
END
当我在 SP 之外运行上述函数时,我得到的日期就好了。当我通过 SP 运行它时,它会以 2012-12-30 00:00:00.000 的形式返回
变量 @CalcDate 被声明为 varchar(10)
有任何想法吗?
提前致谢
编辑
到目前为止,这是 SP 的主体:
declare @StartDate [datetime]
, @EndDate [Datetime]
, @CalcDate [datetime] --This number will change in the WHILE loop to reflect the increment of days
, @Week [varchar]
, @Period [varchar]
, @i [int]
, @Year [int]
, @CalcDay [int]
, @CalcMonth [int]
, @CalcYear [int]
, @ConcatDate [char] (10)
set @StartDate = '2012-12-30'
set @EndDate = '2013-01-28'
set @Year = 2013
set @i = -1
-- Going to do a while loop here and instead of Week number and Period Number I'm going to do some calculations
set @Week = (Select WeekNum from aaGreensPeriodListTest Where PeriodNum = 1 and WeekNum = 1)
set @Period = (Select PeriodNum from aaGreensPeriodListTest Where PeriodNum = 1 and WeekNum = 1)
set @CalcDate = @StartDate + @i
set @CalcMonth = datepart(mm,@calcdate)
insert into aaGreensPeriodTest(RealDate,GreensYear,GreensPeriod,GreensWeek)
values (@CalcDate,@Year,@Period,@Week)
select @CalcDate as CalcDate, @CalcMonth as CalcMonth