[英]How to filter data based on different values of a column in sql server
I am stuck at a point. 我陷入了困境。 I want to select based on the column entitytype if entitytype value is Booking or JOb then it will filter on its basis but if it is null or empty string('') then i want it to return all the rows containing jobs and bookings
如果实体类型的值是Booking或Job,我想根据实体类型列进行选择,那么它将根据其进行过滤,但是如果它为null或为空string(''),那么我希望它返回包含作业和预订的所有行
create proc spproc
@entityType varchar(50)
as
begin
SELECT TOP 1000 [Id]
,[EntityId]
,[EntityType]
,[TenantId]
FROM [FutureTrakProd].[dbo].[Activities]
where TenantId=1 and EntityType= case @EntityType when 'BOOKING' then 'BOOKING'
when 'JOB' then 'JOB'
END
end
Any help would be appreciable 任何帮助都将是可观的
Thankyou 谢谢
create proc spproc
@entityType varchar(50)
as
begin
SELECT TOP 1000 [Id]
,[EntityId]
,[EntityType]
,[TenantId]
FROM [FutureTrakProd].[dbo].[Activities]
where TenantId=1 and (@EntityType is null OR EntityType= @EntityType)
end
You don't need a CASE
expression for this, you just need an OR
. 为此,您不需要
CASE
表达式,只需要一个OR
。 The following should put you on the right path: 以下内容将使您走上正确的道路:
WHERE TenantId=1
AND (EntityType = @EntityType OR @EntityType IS NULL)
Also, note it would also be wise to declare your parameter as NULLable: 另外,请注意将参数声明为NULLable也很明智:
CREATE PROC spproc @entityType varchar(50) = NULL
This means that someone can simply exclude the paramter, value than having to pass NULL
(thus EXEc spproc;
would work). 这意味着某人可以简单地排除参数值,而不必传递
NULL
(因此EXEc spproc;
可以工作)。
Finally, if you're going to have lots of NULLable parameters, then you're looking at a "catch-all" query; 最后,如果您将有许多可为NULL的参数,则需要查看“全部捕获”查询。 the solution would be different if that is the case.
如果是这种情况,解决方案将有所不同。 "Catch-all" queries can be notoriously slow.
众所周知,“全部捕获”查询的速度可能很慢。
You don't need to use case
expression you can do : 您无需使用用
case
表达式即可:
SELECT TOP 1000 [Id], [EntityId], [EntityType], [TenantId]
from [FutureTrakProd].[dbo].[Activities]
WHERE TenantId = 1 AND
(@EntityType IS NULL OR EntityType = @EntityType)
ORDER BY id; -- whatever order you want (asc/desc)
For your query procedure you need to state explicit ORDER BY
clause otherwise TOP 1000
will give random Id
s. 对于您的查询过程,您需要声明显式的
ORDER BY
子句,否则TOP 1000
将给出随机Id
。
You can execute a dynamic sql query. 您可以执行动态sql查询。
Query 询问
create proc spproc
@entityType varchar(50)
as
begin
declare @sql as nvarchar(max);
declare @condition as nvarchar(2000);
select = case when @entityType is not null then ' and [EntityType] = @entityType;' else ';' end;
select @sql = 'SELECT TOP 1000 [Id], [EntityId], [EntityType], [TenantId] FROM [FutureTrakProd].[dbo].[Activities] where TenantId = 1 ';
exec sp_executesql @sql,
N'@entityType nvarchar(1000)',
@entityType = @entityType
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.