无法在案例陈述中使用Sql语句

时间:2017-06-15 15:53:34

标签: sql sql-server

我正在尝试将每周的日期和日期插入表格中。该表应包含30天,不包括星期日。我无法使case语句中的Insert工作。任何帮助将不胜感激。

Declare @StartDate as Date = DateAdd(day,-30,GetDate())
Declare @DOW varchar(10)
Declare @adddaycnt int 
Declare @RecsWrite int
Set @RecsWrite = 0
Set @adddaycnt = 0
While @RecsWrite <= 30
Begin
Select @DOW = DateName(dw,DateAdd(dw,@adddaycnt,@startDate)) 
Select Case When @DOW <> 'Sunday' then 
Insert Into temp_ProdSaleInv (ProdDate,DOW) 
Values(
Convert(varchar(10),DateAdd(day, @adddaycnt,@startDate),101), 
DateName(dw,DateAdd(dw, @adddaycnt,@startDate) 
)
)
End 

Select Case When @DOW <> 'Sunday' then 
Set @RecsWrite = @RecsWrite + 1
Set @adddaycnt = @adddaycnt + 1
Else 
Set @adddaycnt = @adddaycnt + 1
End

2 个答案:

答案 0 :(得分:0)

案例陈述不会像您编码那样有效。请尝试使用IF

Declare @StartDate as Date = DateAdd(day,-30,GetDate())
Declare @DOW varchar(10)
Declare @adddaycnt int 
Declare @RecsWrite int
Set @RecsWrite = 0
Set @adddaycnt = 0
While @RecsWrite <= 30
Begin
Select @DOW = DateName(dw,DateAdd(dw,@adddaycnt,@startDate)) 
IF @DOW <> 'Sunday' 
BEGIN
Insert Into temp_ProdSaleInv (ProdDate,DOW) 
Values(
Convert(varchar(10),DateAdd(day, @adddaycnt,@startDate),101), 
DateName(dw,DateAdd(dw, @adddaycnt,@startDate) 
)
)

END


IF @DOW <> 'Sunday'
BEGIN
   Set @RecsWrite = @RecsWrite + 1
   Set @adddaycnt = @adddaycnt + 1
END
Else 
BEGIN
   Set @adddaycnt = @adddaycnt + 1
END

End

答案 1 :(得分:0)

CASE声明evaluates a list of conditions and returns one of multiple possible result expressions.

相反,您试图在CASE语句中实际运行CRUD语句。

因此,请改用IF条件。