日期:2014-05-18  浏览次数:20554 次

sql中条件判断的语句怎么写啊 If 后不用大括号的啊,不知哪错了我急!!求救!!
Select top 5 vol_ArcType,vol_QZH,Vol_DH,Vol_AJBT,Vol_YS,Vol_BGQX,
 (  
  if (charindex('-',Vol_Date)>0)
  begin
  case
  when len( substring(Vol_Date,1,charindex('-',Vol_Date)-1))=4 then convert(datetime, substring(Vol_Date,1,charindex('-',Vol_Date)-1)+'.01.01',120)
  when len( substring(Vol_Date,1,charindex('-',Vol_Date)-1))=7 then convert(datetime, substring(Vol_Date,1,charindex('-',Vol_Date)-1)+'.01',120)
  else convert(datetime, substring(Vol_Date,1,charindex('-',Vol_Date)-1),120)
  end
  end
  if (charindex('-',Vol_Date)<1)
  begin 
  case
  when len(Vol_Date)=4 then convert(datetime,Vol_Date+'.01.01',120)
  when len(Vol_Date)=7 then convert(datetime,Vol_Date+'.01',120)
  else convert(datetime,Vol_Date,120)
  end
  end
  ) as Vol_BZQSRQ From Table



消息 156,级别 15,状态 1,第 7 行
关键字 'if' 附近有语法错误。
消息 156,级别 15,状态 1,第 9 行
关键字 'case' 附近有语法错误。
消息 156,级别 15,状态 1,第 17 行
关键字 'case' 附近有语法错误。
  哪里错了啊!

------解决方案--------------------
SQL code
Select  top 5 vol_ArcType,vol_QZH,Vol_DH,Vol_AJBT,Vol_YS,Vol_BGQX, 
(    
    case when charindex('-',Vol_Date)>0  
       then
          case 
            when len( substring(Vol_Date,1,charindex('-',Vol_Date)-1))=4 then convert(datetime, substring(Vol_Date,1,charindex('-',Vol_Date)-1)+'.01.01',120) 
            when len( substring(Vol_Date,1,charindex('-',Vol_Date)-1))=7 then convert(datetime, substring(Vol_Date,1,charindex('-',Vol_Date)-1)+'.01',120) 
            else convert(datetime, substring(Vol_Date,1,charindex('-',Vol_Date)-1),120) 
          
      
     when charindex('-',Vol_Date) <1
     then 
        case 
            when len(Vol_Date)=4 then convert(datetime,Vol_Date+'.01.01',120) 
            when len(Vol_Date)=7 then convert(datetime,Vol_Date+'.01',120) 
            else convert(datetime,Vol_Date,120) 
          
      end 
  ) as Vol_BZQSRQ From Table

------解决方案--------------------
SQL code

这样试试
Select  top 5 vol_ArcType,vol_QZH,Vol_DH,Vol_AJBT,Vol_YS,Vol_BGQX, 
( case   
    when (charindex('-',Vol_Date)>0) then
       
          case 
            when len( substring(Vol_Date,1,charindex('-',Vol_Date)-1))=4 then convert(datetime, substring(Vol_Date,1,charindex('-',Vol_Date)-1)+'.01.01',120) 
            when len( substring(Vol_Date,1,charindex('-',Vol_Date)-1))=7 then convert(datetime, substring(Vol_Date,1,charindex('-',Vol_Date)-1)+'.01',120) 
            else convert(datetime, substring(Vol_Date,1,charindex('-',Vol_Date)-1),120) 
          end 
       
    when (charindex('-',Vol_Date) <1) then
       
        case 
            when len(Vol_Date)=4 then convert(datetime,Vol_Date+'.01.01',120) 
            when len(Vol_Date)=7 then convert(datetime,Vol_Date+'.01',120) 
            else convert(datetime,Vol_Date,120) 
          end 
       
  end) as Vol_BZQSRQ From Table