我正在尝试计算SQL Server 2008中两个日期之间状态为0的记录 有我的程序,但它不正确的错误。
Msg 156,Level 15,State 1,Procedure sp_SerchPickupHispanicBetweenDates,Line 6
之间的语法不正确
关键字“'。
程序看起来像
CREATE procedure sp_SerchPickupHispanicBetweenDates
@date1 date,
@date2 date
as
select COUNT ( Pickuphispanic ) from pickup
where Pickuphispanic = 1 and pickupdate like between @date1+ '%' and @date1 +'%'
正在互联网上尝试搜索解决方案,但没有成功。 任何想法如何纠正它是正确的? 我也有选择完美的法则
select COUNT ( Pickuphispanic ) from pickup
where Pickuphispanic = 1 and pickup.pickupdate between '2006-07-01' and '2010-12-31'
答案 0 :(得分:4)
@date1
和@date2
参数的数据类型为DATE
,因此您无法将%
附加到这些值(%
可以在使用LIKE
运算符时,仅用于基于字符串的数据类型;另外: 不能将LIKE
应用于使用DATE
值的搜索
请改用:
CREATE procedure procSerchPickupHispanicBetweenDates
@date1 date,
@date2 date
AS
SELECT COUNT (Pickuphispanic)
FROM dbo.pickup
WHERE Pickuphispanic = 1
AND pickupdate BETWEEN @date1 AND @date2
要调用此方法,请使用以下语法:
EXEC procSerchPickupHispanicBetweenDates '2006-07-01', '2010-12-31'
(没有大括号,没有括号 - 只需指定两个日期),或者:
EXEC procSerchPickupHispanicBetweenDates @date1 = '2006-07-01', @date2 = '2010-12-31'
答案 1 :(得分:2)
如果您尝试在两个日期之间进行搜索,则您的存储过程必须如下所示:
pickupdate between @date1 and @date2
你没有必要使用类似的功能
答案 2 :(得分:1)
喜欢无法嵌套在之间功能。
试试这个:
CREATE procedure sp_SerchPickupHispanicBetweenDates
@date1 date,
@date2 date
as
select COUNT ( Pickuphispanic ) from pickup
where Pickuphispanic = 1 and CONVERT(VARCHAR(25), pickupdate , 126) like @date1 + '%' and @date1 + '%'
此致
答案 3 :(得分:1)
像这样修改查询:
SELECT COUNT ( Pickuphispanic_ID ) from pickup
where Pickuphispanic = 1 and pickupdate between @date1 AND @date2
或
SELECT COUNT ( Pickuphispanic_ID ) from pickup
where Pickuphispanic = 1 and pickupdate> @date1 AND pickupdate<@date2
答案 4 :(得分:0)
喜欢不能嵌套在Between Function之间。
如果你想像那样使用它应该是这样的
CREATE procedure sp_SerchPickupHispanicBetweenDates
@date1 date,
@date2 date
as
select COUNT ( Pickuphispanic ) from pickup
where Pickuphispanic = 1 and (CONVERT(VARCHAR, pickupdate ,106) like CONVERT(VARCHAR,@date1,106) + '%' or CONVERT(VARCHAR, pickupdate ,106) like CONVERT(VARCHAR,@date2,106) + '%')
你希望在它之间使用它应该是这样的
CREATE procedure procSerchPickupHispanicBetweenDates
@date1 date,
@date2 date
AS
SELECT COUNT (Pickuphispanic)
FROM dbo.pickup
WHERE Pickuphispanic = 1
AND Convert(date,pickupdate) BETWEEN Convert(date,@date1) AND Convert(date,@date2)