2013-02-25 63 views
0

如果@ UserRoleId = 4,我需要在WHERE子句中添加一個條件,否則將它們排除在搜索之外(SQL Server)。Where子句中的可選條件語句

INSERT INTO @partData 
(
    PartPrefix, 
    PartNumber, 
    MyProDescription, 
    ItemNumber, 
    PartType, 
    Side, 
    VehicleLocation, 
    MyProPrice 
) 
SELECT 
    CASE 
    WHEN LEFT(myParts.MyProDescription, 4) = 'FOIL' THEN 'FOIL' 
    ELSE LEFT(myParts.PartNumber, 3) 
    END, 
    PartNumber, 
    MyProDescription, 
    ItemNumber, 
    PartType, 
    Side, 
    VehicleLocation, 
    MyProPrice 
FROM 
    MyProExport myParts 
WHERE 
    @year BETWEEN myParts.YearFrom AND myParts.YearTo AND 
    myParts.CarMake = @make AND 
    REPLACE(myParts.CarModel, ' ', '') = REPLACE(@model, ' ', '') AND 
    (
    myParts.EngineDisplacement = @engine OR 
    myParts.EngineDisplacement = 'ALL' 
) AND 
    LEFT(myParts.PartNumber, 3) NOT IN ('300','400') -- Exclude these parts if not @UserRoleId = 4 

最後一條語句需要修改,以顯示300和400僅@UserRoleId是= 4。否則只顯示300我如何設置此困惑。我已經試過:

CASE 
    WHEN @UserRoleId = 4 THEN LEFT(myParts.Number, 3) NOT IN ('300','400') -- Exclude parts 

,沒有運氣...

回答

1

而是一個case語句,只需使用和/或邏輯。

AND (LEFT(myParts.HollanderNumber, 3) = '300' 
OR (@UserRoleID = 4 AND LEFT(myParts.HollanderNumber, 3) = '400')) 

這將始終顯示300,只顯示400,如果@UserRoleID = 4

+0

好,我現在就試試 – devHead 2013-02-25 16:54:01

+0

它的工作,但只有回到300的時候不要UserRoleId是4只返回400級的時候UserRoleId是4 ...我還需要包含其他前綴(如'200','500'(更多)的其他部分),如果我的帖子不夠,我很抱歉。 – devHead 2013-02-25 17:25:03

+0

有一些改動,因爲我需要它的工作。謝謝! – devHead 2013-02-25 18:54:00