案例陈述T-SQL

时间:2013-02-12 15:47:09

标签: sql-server tsql case

下面的脚本一切正常,直到我尝试添加带有SELECT子句的Case语句我已经这样做以自动填充表格的正确日期可以让我知道我做错了什么?

DECLARE @PitchType_Skey INT
DECLARE @Site_Skey INT
DECLARE @Capacity INT
DECLARE @StartDate DATE
DECLARE @EndDate DATE

SET @PitchType_Skey = 1
SET @Site_Skey = 1
SET @Capacity = 0

WHILE (@Site_Skey < 127)

BEGIN
    IF @PitchType_Skey = 8

BEGIN

SET @PitchType_Skey = 1
SET @Site_Skey = @Site_Skey + 1

END

IF (@Site_Skey < 127)

BEGIN

Set @Capacity = (SELECT SiteWeighting From Site Where Site_Skey = @Site_Skey)
Set @Capacity = @Capacity * (SELECT PitchTypeWeighting From PitchType  Where PitchType_Skey = @PitchType_Skey)
Set @Capacity = @Capacity * ((10*(100+((RAND()*40)-20)))*0.01)

     INSERT INTO Capacity 
     SELECT
     CASE @StartDate
     WHEN (SELECT SiteWeighting FROM Site WHERE SiteWeighting = 1 THEN 01/05/2010) ELSE,
     WHEN (SELECT SiteWeighting FROM Site WHERE SiteWeighting = 2 THEN 01/04/2010) ELSE,
     WHEN (SELECT SiteWeighting FROM Site WHERE SiteWeighting = 3 THEN 01/04/2010) ELSE,
     WHEN (SELECT SiteWeighting FROM Site WHERE SiteWeighting = 4 THEN 01/01/2010) ELSE,

     CASE @EndDate
     WHEN (SELECT SiteWeighting FROM Site WHERE SiteWeighting = 1 THEN 30/09/2010) ELSE,
     WHEN (SELECT SiteWeighting FROM Site WHERE SiteWeighting = 2 THEN 01/11/2010) ELSE,
     WHEN (SELECT SiteWeighting FROM Site WHERE SiteWeighting = 3 THEN 01/11/2010) ELSE,
     WHEN (SELECT SiteWeighting FROM Site WHERE SiteWeighting = 4 THEN 01/12/2010) ELSE,

      round(@Capacity,0) as Capacity,
      @PitchType_Skey, @Site_Skey

END
  SET @PitchType_Skey = @PitchType_Skey + 1

END

1 个答案:

答案 0 :(得分:2)

嗯,你的括号在错误的地方。 THEN是case语句的一部分,但是你在子查询中有它。您还只需要一个ELSE个案例陈述。

如果不了解更多关于你的表的话,很难知道是否有更多错误,但语法正确的case语句看起来像这样:

CASE @StartDate
  WHEN (SELECT SiteWeighting FROM Site WHERE Site_SKey=@Site_SKey)=1 THEN '01/05/2010'
  WHEN (SELECT SiteWeighting FROM Site WHERE Site_SKey=@Site_SKey)=2 THEN '01/04/2010'
  ELSE NULL 
END

但是,我强烈建议您不要使用case语句。相反,请使用其他内容,例如具有基于SiteWeighting可以加入的开始日期和结束日期的查找表。它会让你的生活更轻松。