LocationID LocationName
50 Sharjah
51 Qatar
55 Rigga
6 Dubai Mall
我需要创建以locationId
为参数的sql查询,
如果locationId
传递0,那么我想显示所有这些记录,否则按照locationId
传递。
我尝试过case case但没有成功。
答案 0 :(得分:0)
试试这个:这里@Parm
会将值传递给您的脚本
SELECT *
FROM TableName
WHERE (@Parm = 0 OR LocationID = @Parm)
答案 1 :(得分:0)
DECLARE @locationId INT;
SELECT LocationID, LocationName
FROM yourTable
WHERE @locationId = 0 OR LocationID = @locationId
答案 2 :(得分:0)
我为你创建了一个存储过程。
CREATE TABLE #LOCATIONS
(
LocationID INT
,LocationName VARCHAR(100)
)
INSERT INTO #LOCATIONS VALUES(
50,'Sharjah')
,(51,'Qatar')
,(55,'Rigga')
,(6,'Dubai Mall')
SELECT * FROM #LOCATIONS
GO
CREATE PROC LOC ( @LOC_ID INT )
AS
BEGIN
IF(@LOC_ID = 0)
SELECT * FROM #LOCATIONS
ELSE
SELECT * FROM #LOCATIONS WHERE LocationID = @LOC_ID
END
GO
EXEC LOC 0 -- Try Executing the stored proc like this
EXEC LOC 55 -- Try Executing the stored proc like this