SQL Server:给定一年找到前一年和给定年份的所有内容(包括)

时间:2011-02-18 16:32:55

标签: php sql sql-server tsql

我不熟悉SQL Server语法,但我想它会是这样的:

$year = 2010;

$query = mssql_query("SELECT * FROM dbo.events 
                      WHERE date BETWEEN $year AND $year-1");

在这种情况下,我只是不确定如何格式化$ year。

4 个答案:

答案 0 :(得分:3)

你很亲密。假设date列是datetime数据类型:

SELECT *
    FROM dbo.events
    WHERE DATEPART(year, date) BETWEEN $year-1 AND $year

答案 1 :(得分:1)

SQL Server有YEAR function,写入比DATEPART更短:

select * from dbo.events where year(date) between $year-1 and $year

答案 2 :(得分:1)

你试图只选择一年吗?

这对我有用:

$year = 2011;
select * from table where year(date_field) = $year

答案 3 :(得分:0)

试试这个:

declare @year int
set @year=2010

select * from FROM dbo.events 
WHERE cast(YEAR([date]) as int) <= @year 
and cast(YEAR([date]) as int) >= @year-1