select @date_string = cast(@year as varchar)+"-"+cast(@month as varchar)+"-"+"01"
set @date_string = cast(@date_string AS DATETIME)
set @checktime_end = dateadd(day,-1,@date_string)
set @checktime_start = dateadd(day,-2,@date_string) --在這個地方寫你要查詢的內容[table]是你的表,[date]是時間列,還有別的條件你自己加
set @sql = @sql + "select * from [table] where [date] between """+cast(@checktime_start AS varchar(16))+""" and """+ cast(@checktime_end AS varchar(16))+ """ union all "
set @month = @month +1
end
set @sql = @sql + "select * from [table] where [date] between ""12 30 2009 12:00AM"" and ""12 31 2009 12:00AM"""
我寫了下面的語句供你參考,涉及到的內容:1、cast() 資料型別轉換2、跳脫字元 (""),兩個單引號代表一個單引號3、while 迴圈4、union all 查詢連線 declare @day int
declare @month int
declare @year int
declare @date_string varchar(20)declare @checktime_start datetime
declare @checktime_end datetimedeclare @sql varchar(2048)set @year = 2009
set @month = 2
set @sql = ""
while(@month
begin
select @date_string = cast(@year as varchar)+"-"+cast(@month as varchar)+"-"+"01"
set @date_string = cast(@date_string AS DATETIME)
set @checktime_end = dateadd(day,-1,@date_string)
set @checktime_start = dateadd(day,-2,@date_string) --在這個地方寫你要查詢的內容[table]是你的表,[date]是時間列,還有別的條件你自己加
set @sql = @sql + "select * from [table] where [date] between """+cast(@checktime_start AS varchar(16))+""" and """+ cast(@checktime_end AS varchar(16))+ """ union all "
set @month = @month +1
end
set @sql = @sql + "select * from [table] where [date] between ""12 30 2009 12:00AM"" and ""12 31 2009 12:00AM"""
--print(@sql)
exec @sql
這個是按你要求只查詢2009年的記錄,假如你要查2005到2009,你在while迴圈外面再加個對年的迴圈。