2013-07-30 55 views
10

在SQL Server Management Studio中,我试图引用特定的日期和时间,使用变量作为日期,如下所示。在SQL中设置变量日期

Declare @specified_date Date 
set @specified_date = '07-01-2013' 

Select * 
from etc 
Where CreatedDate > CONVERT(datetime, @specified_date & '00:00:00.000') 

此代码不能正常工作,而且我收到此错误:使用

The data types date and varchar are incompatible in the '&' operator.

的数据上有两个日期和时间码,而不是改变多个查询,我我希望能够只定义一次日期,并让变量带着它。如果有人知道解决方案,那会很棒。

+0

我会推荐**总是**如果您将日期指定为字符串 - 即YYYY-MM-DD格式,请使用ISO-8601格式化日期。只有该格式才能保证可以在任何语言和/或日期格式设置的所有SQL Server实例上工作。其他任何*可能*在正确的设置下工作,但在另一个设置不同的系统上使用时可能会出现可怕的错误 –

回答

16

你有没有尝试这个办法:

Declare @specified_date Date 
set @specified_date = '07-01-2013' 
Select * from etc 
Where CreatedDate > @specified_date 
+0

不,但是您给了我一个有效的想法!谢谢了,这就是我最后的结果 – Dakota

+0

因为给我添加代码很困难,所以基本上声明有一天是A,下一个是B,然后在A和B之间选择* – Dakota

3

使用的+,而不是&。您还必须投射字符串以使其成为日期时间。

Declare @specified_date Date 
set @specified_date = '07-01-2013' 
Select * from etc 
Where CreatedDate > CONVERT(datetime, @specified_date + cast('00:00:00.000' as datetime)) 
+1

谢谢!保存这个......我很习惯在VBA编码,很难不使用&lol来连接事物 – Dakota