[英]Check if a certain value exist in the passed parameter in query (SQL SERVER)
So I need to determine if a certain value exist in the passed parameter to perform a certain condition. 因此,我需要确定传递的参数中是否存在某个值才能执行某种条件。 Here's the query below:
这是下面的查询:
DECLARE @PCStatusas varchar(50);
SELECT * FROM
Employee emp
WHERE (emp.PCStatus IN (@PCStatus) OR @PCStatus = '')
OR
('ON-HOLD' IN (@PCStatus)
('ON-HOLD'IN(@PCStatus)
AND CAST(emp.EffectiveDate AS DATE) <= CAST(GETDATE() AS DATE)))
so what i need is to check if the parameter sent contain the value 'ON-HOLD' to perform the EffectiveDate condition being equal or less than today. 因此,我需要检查发送的参数是否包含值“ ON-HOLD”,以执行等于或小于今天的EffectiveDate条件。
You can do like (@PCStatus like '%ON-HOLD%')
您可以这样做
(@PCStatus like '%ON-HOLD%')
DECLARE @PCStatusas varchar(50);
SELECT * FROM
Employee emp
WHERE (emp.PCStatus IN (@PCStatus) OR @PCStatus = '')
OR
(@PCStatus like '%ON-HOLD%')
AND CAST(emp.EffectiveDate AS DATE) <= CAST(GETDATE() AS DATE)))
If you have mix AND
and OR
conditions, it is best to use parenthesis ( )
on it to clearly define the intended conditions. 如果您具有混合
AND
和OR
条件,则最好在其上使用括号( )
清楚地定义预期条件。
Also avoid applying function on the column as it will prohibit the use of index on the column. 还要避免在列上应用函数,因为这将禁止在列上使用索引。 If the EffectiveDate does not contain time, you may simply use equal
emp.EffectiveDate = CAST(GETDATE() AS DATE)
else you should use >= today
and < tomorrow
如果EffectiveDate不包含时间,则可以简单地使用等于
emp.EffectiveDate = CAST(GETDATE() AS DATE)
否则应使用>= today
和< tomorrow
DECLARE @PCStatus as varchar(50);
SELECT *
FROM Employee emp
WHERE
(
emp.PCStatus = @PCStatus
)
OR
(
@PCStatus = ''
)
OR
(
@PCStatus LIKE '%ON-HOLD%'
AND emp.EffectiveDate >= CAST(GETDATE() AS DATE)
AND emp.EffectiveDate < CAST(DATEADD(DAY, 1, GETDATE()) AS DATE)
)
EDIT : change to LIKE '%ON-HOLD%'
编辑:更改为
LIKE '%ON-HOLD%'
EDIT 2 : @PCStatus is CSV here, the query is using STRING_SPLIT()
if you are using earlier version of SQL Server, use the DelimitedSplit8K
that i posted in the comments 编辑2:@PCStatus在此处为CSV,如果您使用的是SQL Server的早期版本,则查询使用的是
STRING_SPLIT()
,请使用我在评论中发布的DelimitedSplit8K
DECLARE @PCStatus as varchar(50) = 'ACTIVE,ON-HOLD';
SELECT *
FROM Employee emp
WHERE
(
@PCStatus = ''
OR EXISTS
(
select *
from STRING_SPLIT(@PCStatus, ',') x
where x.value = emp.PCStatus
)
)
AND
(
emp.PCStatus <> 'ON-HOLD'
OR emp.EffectiveDate <= CAST(GETDATE() AS DATE)
)
So with the help of my colleague, we created a function that splits the csv into a temporary table and there I can simply check if a certain value is in the temporary table and return a Boolean for it. 因此,在同事的帮助下,我们创建了一个将csv拆分为临时表的函数,在那里我可以简单地检查临时表中是否有某个值并为其返回布尔值。 Thanks for the help guys.
感谢您的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.