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

SQL查询语句报错'2012' 附近有语法错误,请朋友们指点哪里错了呀?
declare @SQL VARCHAR(MAX)
DECLARE @Wherestring VARCHAR(MAX)
SET @Wherestring=' and a.CreateDate between ''2012-5-3 0:00:00'' and ''2012-5-3 23:59:59'' '


SET @SQL= ' SELECT  
 (case a.OperateType when ''aa'' then a.NewCardNo else '' end) as bb,a.OldCardNo as cc 
  FROM dbo.CardRevisionHistoryOfResetCard as a LEFT JOIN dbo.Organization as b on a.OID = b.OrganizationID  
WHERE 1 = 1 '+@Wherestring+' UNION ALL '
SET @SQL=@SQL+' SELECT  
 (case a.OperateType when ''aa'' then a.NewCardNo else '' end) as bb,a.OldCardNo as cc 
  FROM dbo.CardRevisionHistoryOfResetCard as a 
INNER JOIN CardInfo as c ON a.OldCardNo = c.CardNo or a.NewCardNo=c.CardNO LEFT JOIN dbo.Organization as b on a.OID = b.OrganizationID  
WHERE 1 = 1 and c.IsLoss=0 and c.IsUntread=0 and c.CardTypeCode=1 '+@Wherestring+' '  


消息 102,级别 15,状态 1,第 4 行
'2012' 附近有语法错误。


------解决方案--------------------
CASE中为空需要''''不是''
SQL code

SET @SQL= ' SELECT  
 (case a.OperateType when ''aa'' then a.NewCardNo else '''' end) as bb,a.OldCardNo as cc 
  FROM dbo.CardRevisionHistoryOfResetCard as a LEFT JOIN dbo.Organization as b on a.OID = b.OrganizationID  
WHERE 1 = 1 '+@Wherestring+' UNION ALL '
SET @SQL=@SQL+' SELECT  
 (case a.OperateType when ''aa'' then a.NewCardNo else '''' end) as bb,a.OldCardNo as cc 
  FROM dbo.CardRevisionHistoryOfResetCard as a 
INNER JOIN CardInfo as c ON a.OldCardNo = c.CardNo or a.NewCardNo=c.CardNO LEFT JOIN dbo.Organization as b on a.OID = b.OrganizationID  
WHERE 1 = 1 and c.IsLoss=0 and c.IsUntread=0 and c.CardTypeCode=1 '+@Wherestring+' '

------解决方案--------------------
else '' -> else ''''