SQL Query数据基于变量

SBB*_*SBB 1 sql sql-server stored-procedures

我有一个简单的查询,我正在尝试适应新的情况.对于这种情况,如果变量locationID=1那么我需要所有记录,不管它是什么locationID.

但是,如果它不相等1,我只需要提供与之匹配的记录@locationID.

这是我的设置示例:

DECLARE @locationID INT = 1; -- All Results Regardless of locationID
--DECLARE @locationID INT = 2; -- Only results that match this locationID (2)
--DECLARE @locationID INT = 3; -- Only results that match this locationID (3)

-- Temp Data
DECLARE @temp AS TABLE (color VARCHAR(10), locationID INT, name VARCHAR(20))
INSERT INTO @temp( color, locationID, name  )VALUES  ( 'Blue', 1, 'Test 1' )
INSERT INTO @temp( color, locationID, name ) VALUES  ( 'Red', 2, 'Test 2' )
INSERT INTO @temp( color, locationID, name ) VALUES  ( 'Red', 1, 'Test 3' )
INSERT INTO @temp( color, locationID, name ) VALUES  ( 'Red', 2, 'Test 4' )
INSERT INTO @temp( color, locationID, name ) VALUES  ( 'Red', 3, 'Test 5' )

-- Query
SELECT * 
FROM @temp
WHERE
locationID = ...
Run Code Online (Sandbox Code Playgroud)

我想弄清楚我是否需​​要使用一种CASE WHEN或其他方法.

Abd*_*had 7

WHERE (locationID = @LocationId OR @locationID = 1)
Run Code Online (Sandbox Code Playgroud)