带有case语句,子查询的存储过程

时间:2011-07-13 21:42:07

标签: sql sql-server-2008

if
@Status = '0' and @Complaint<> '0'
WITH NewTable As
    (

        Select sno = ROW_NUMBER()OVER (order by complaint_id), Complaint_Id, Complaint.ComplaintType_id, Complaint.complaintProfileId, Complaint.Description, 
                            Complaint.Email, Complaint.PriorityLevel_id, Complaint.Date_Complained, Complaint.Status, Complaint.AdminComments, Complaint.Phone, Complaint.Evidence
                from Complaints Complaint ),

with two as 
if exists(select profile_id from MMBmembership
where profile_id = ComplaintProfileId)
select  MMB_Name as @Name from MMB_BusinessProfiles where MMBId= (select MMB_id from MMBMembership
where profile_id  = ComplaintProfileId )

if exists(select profile_id from UPPMembership
where profile_id = ComplaintProfileId)


set @Name = 'UPP'
else
set @name = 'Not Found'



SELECT * FROM NewTable,@Name   left outer join two on 
newtable.complaintProfileid = two.ProfileId 
WHERE (ComplaintType_id = @Complaint) ORDER BY Date_Complained desc ,PriorityLevel_id

Thanks
Sun

1 个答案:

答案 0 :(得分:0)

除非我误解,否则我认为你不需要SUB查询。你只需要LEFT JOIN,是的你可以使用CASE语句

 SELECT  
      CASE 
           WHEN MMB_Name IS NOT NULL THEN MMB_Name  
           WHEN UPPMembership.profile_id  IS NOT NULL THEN 'UPP'
           ELSE 'Not found'
      END as Name
  FROM Complaints Complaint
     LEFT JOIN  MMBMembership 
     ON MMBMembership.profile_id = Complaint.complaintProfileId
     LEFT JOIN UPPMembership
     ON UPPMembership.profile_id = Complaint.complaintProfileId