Sql Server错误 - 条件附近的语法不正确

时间:2014-02-18 09:39:53

标签: sql-server-2008

我的查询如下所示:

declare @test varchar(500)
 SELECT @test=coalesce(@test+',','') + cast(RoleName as varchar) FROM                                                               
        (   select roles.RoleName  from LU_BCOMS_usersroles usrroles
            inner join LU_BCOMS_roles roles 
            on roles.roleid     =   usrroles.Roles_roleid 
            where Users_Userid='MV10310'
        ) as Tbl

select repfamily.ProductName as Category,repfamily.Family as SeqChange,repfamily.RepFamily as DescOfChange, req.*,
 TaskCompVer =
 CASE WHEN req.UpdateByASPM is not null THEN  'Provide PLQM Wish List'
        WHEN req.UpdateByASPM  is null THEN 'Provide ASPM Wish List'
        WHEN req.CreatedBy is not null THEN  'Provide ASPM Wish List'
        END
  from performa.TX_BCOMS_Request as req   
inner join TX_BCOMS_Requestrepfamily family on 
family.request_requestid=req.requestid
inner  join LU_BCOMS_RepFamily as repfamily on 
family.RepFamily_repFamilyid=repfamily.repfamilyid   

where req.UpdatedByPLQM is null  
 (
   if (CHARINDEX('ASPM',@test)> 0 )
         Begin 
         and  req.UpdatedByASPM is null
         end
   else if (CHARINDEX('PLQM' ,@test)> 0)
         begin
         and req.UpdatedByASPM IS NOT null
         END 
  )

我无法构建查询,因为它附近有错误的语法。如果有任何人可以帮助我解决这个问题。

如果我符合这个条件,如果(CHARINDEX('ASPM',@ test)> 0)我需要添加“and req.UpdatedByASPM is null”或者下一个...

2 个答案:

答案 0 :(得分:1)

我认为你期待这个,,,

declare @test varchar(500)
 SELECT @test=coalesce(@test+',','') + cast(RoleName as varchar) FROM                                                               
        (   select roles.RoleName  from LU_BCOMS_usersroles usrroles
            inner join LU_BCOMS_roles roles 
            on roles.roleid     =   usrroles.Roles_roleid 
            where Users_Userid='MV10310'
        ) as Tbl

select repfamily.ProductName as Category,repfamily.Family as SeqChange,repfamily.RepFamily as DescOfChange, req.*,
 TaskCompVer =
 CASE WHEN req.UpdateByASPM is not null THEN  'Provide PLQM Wish List'
        WHEN req.UpdateByASPM  is null THEN 'Provide ASPM Wish List'
        WHEN req.CreatedBy is not null THEN  'Provide ASPM Wish List'
        END
  from performa.TX_BCOMS_Request as req   
inner join TX_BCOMS_Requestrepfamily family on 
family.request_requestid=req.requestid
inner  join LU_BCOMS_RepFamily as repfamily on 
family.RepFamily_repFamilyid=repfamily.repfamilyid   

where req.UpdatedByPLQM is null   and (

   ((CHARINDEX('ASPM',@test)> 0 )  and  req.UpdatedByASPM is null)
   or 
   ((CHARINDEX('PLQM' ,@test)> 0)  and req.UpdatedByASPM IS NOT null)
   )

答案 1 :(得分:0)

尝试使用where子句区域

WHERE   req.UpdatedByPLQM Is Null
        And 
        (CASE
            WHEN CHARINDEX('ASPM',@test)> 0 and req.UpdatedByASPM Is Null THEN 1
            WHEN (CHARINDEX('PLQM' ,@test)> 0) and req.UpdatedByASPM Is Not Null THEN 1
            ELSE 0
        END) = 1