2016-11-10 121 views
0

我寫一個存儲過程在SQL Server 2014在AND構建SQL查詢與NULL檢查

下面

CREATE PROCEDURE [dbo].[GetUsers] 
@Role INT 
    SELECT FirstName, LastName 
    FROM Users 
    WHERE FirstName = 'Something' 
    IF NULLIF(@Role, '') IS NOT NULL  
    BEGIN 
     AND Role = @Role 
    END 
END 

,並配合這一點,是扔語法錯誤我要動態地構建查詢並排除NULL''的值

回答

1

您不能構建這樣的動態查詢。但是你可以使用布爾邏輯

SELECT FirstName, LastName 
FROM Users 
Where FirstName = 'Something' 
AND (@Role is null or @Role = '' or Role = @Role)