CREATE TABLE #MyTasks
(TaskId int,
CompanyId int,
YearCol varchar(50),
MonthCol varchar(50),
SomeValue varchar(50)
);
GO
INSERT INTO #MyTasks
SELECT 220,1,2018,1,50553.32
UNION
SELECT 220,2,2018,2,222038.12
DECLARE @Param1 int = 1
DECLARE @Param2 int = 0
SELECT * FROM #MyTasks
WHERE
(@Param1 != 0 AND taskid in (select taskid from #mytasks where companyid = @param1) OR @Param1 = 0)
OR
(@Param2 != 0 AND taskid in (select taskid from #mytasks where companyid = @param2) OR @Param2 = 0) -- because of this condition, all rows are being returned
如果@ Param1没有传递给存储过程,如何从#MyTasks表返回所有行?我最初将其设置为0,并且仅在通过且与0有所不同时才想使用where子句。
答案 0 :(得分:3)
只需在where子句上使用一些括号并添加一个print (model_dict)
{'Select Model': ['empty', None], 'Jet Fighter': ['MODEL1_530', 'NOT_AVAILABLE'], 'Jet Fighter2': ['MODEL2_540', 'NOT_AVAILABLE']}
条件。
OR
这可以进一步简化为
WHERE
(@Param1 != 0 AND taskid in (select taskid from #mytasks where companyid = @Param1))
or @Param1 = 0 --usually this would be IS NULL
或具有多个参数...
WHERE companyid = @Param1 or @Param1 = 0
答案 1 :(得分:0)
如果您在同一张桌子上工作,请不要使用不使用或仅在where子句中使用它,因为它两次都不会读取完整表。
可以通过以下方式完成:
CREATE TABLE #MyTasks
(TaskId int,
CompanyId int,
YearCol varchar(50),
MonthCol varchar(50),
SomeValue varchar(50)
);
GO
INSERT INTO #MyTasks
SELECT 220,1,2018,1,50553.32
UNION
SELECT 220,2,2018,2,222038.12
DECLARE @Param1 int = 0
SELECT * FROM #MyTasks
WHERE @param1 = 0 or companyid = @param1