SQL查询在服务器上不起作用

时间:2016-01-19 11:28:01

标签: sql-server tsql sql-server-2008-r2

this is on server query imageThis is on local DB query image我正在尝试执行SQL查询。对于生日,它在本地数据库上工作正常,但在服务器上它不提供任何输出:

SELECT studentname
      ,CONVERT(VARCHAR ,birthday ,101)
FROM   birthday
WHERE  DATEADD(
           YEAR
          ,DATEPART(YEAR ,GETDATE())- DATEPART(YEAR ,birthday)
          ,birthday
       ) BETWEEN CONVERT(DATE ,GETDATE()) AND CONVERT(DATE ,GETDATE()+7);

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

我认为你犯了一个小错误,

SELECT studentname
      ,CONVERT(VARCHAR ,birthday ,101)
FROM   TableName --here it should be table name not the field name
WHERE  DATEADD( 
           YEAR
          ,DATEPART(YEAR ,GETDATE())- DATEPART(YEAR ,birthday)
          ,birthday
       ) BETWEEN CONVERT(DATE ,GETDATE()) AND CONVERT(DATE ,GETDATE()+7)

所以我检查了你的图像,它清楚地表明你在那里放错了条件。

见下图并用15替换7以显示数据。

enter image description here

<强>更新

告诉我以下查询返回的内容,

Select DATEADD( YEAR ,DATEPART(YEAR ,GETDATE())- DATEPART(YEAR ,birthday),birthday)

它会告诉你,

2016-01-29
2016-01-30
2016-01-31
2016-02-01

执行以下查询,

SELECT CONVERT(DATE ,GETDATE())
2016-01-21

SELECT CONVERT(DATE ,GETDATE() + 7)
2016-01-28

你符合你的条件,怎样才能满足你的条件?

如果您能理解,请参阅以下查询,

CREATE TABLE #Temp (StudentName VARCHAR(100),StudentId int,birthday date);
INSERT INTO #Temp (StudentName,StudentId,birthday)
VALUES('tapan',5,'1997-01-29'),
('karan',6,'1997-01-30'),
('ravi',7,'1997-01-31'),
('anand',8,'1997-02-01')
SELECT studentname
      ,CONVERT(VARCHAR ,birthday ,101)
FROM   #Temp --here it should be table name not the field name
WHERE  DATEADD( 
           YEAR
          ,DATEPART(YEAR ,GETDATE())- DATEPART(YEAR ,birthday)
          ,birthday
       ) BETWEEN '2016-01-21' AND '2016-01-28'

SELECT studentname,CONVERT(VARCHAR ,birthday ,101), DATEADD( YEAR ,DATEPART(YEAR ,GETDATE())- DATEPART(YEAR ,birthday),birthday) as WhereConditionField FROM #Temp
SELECT DATEADD( YEAR ,DATEPART(YEAR ,GETDATE())- DATEPART(YEAR ,birthday),birthday) as testcolumn FROM #Temp
SELECT CONVERT(DATE ,GETDATE())
SELECT CONVERT(DATE ,GETDATE() + 7)
DROP TABLE #Temp