检查字符串的第一部分是否存在于表中的值列表中



被隔离这么久后,我有点头脑空白,无法解决这个简单的问题。

我在表格中有一个值列表。我想检查@variable中文本的第一部分是否包含表中的任何值。当它是完全匹配时它可以工作,但我不确定在针对部分字符串时如何处理它。

CREATE TABLE [ExclusionCriteria](
[ID] [uniqueidentifier] NOT NULL,
[Criteria] [nvarchar](100) NOT NULL,
CONSTRAINT [PK_ExclusionCriteria] PRIMARY KEY CLUSTERED 
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [ExclusionCriteria] ADD  CONSTRAINT [DF_ExclusionCriteria_ID]  DEFAULT (newid()) FOR [ID]
INSERT INTO [ExclusionCriteria] (Criteria)
VALUES ('Test1'), ('Test2'),('Another string'),('Test string 4')
DECLARE @TestValue NVARCHAR(100) = 'Test1 but with some more text on the end'
SELECT * FROM ExclusionCriteria WHERE Criteria LIKE @TestValue

我希望它匹配,因为@TestValue的第一部分Test1其中。我尝试使用子字符串,但根据匹配的内容,"标准"的长度总是不同的。

我想我想做一些类似于列表中的"foreach"的事情,但无法弄清楚如何使用 SQL 执行此操作。这将是某些逻辑的一部分,因此需要遵循if @TestValue Begins With (any of the values in [ExclusionCriteria]) true else false

SQL可以做到这一点吗,还是我将不得不改变我的方法?我宁愿不必将所有值硬编码到一个长IN语句中。

您需要反转顺序并添加尾随通配符

SELECT * 
FROM ExclusionCriteria 
WHERE @TestValue LIKE Criteria + '%'

如果ExclusionCriteria很大并且Criteria已编制索引,则可以在AND Criteria LIKE LEFT(@TestValue,1) + '%'上添加额外的谓词,以便从查找中获得一定的好处并避免读取所有行。

DECLARE     @ExclusionCriteria  TABLE   ([Criteria] [nvarchar](100))
INSERT INTO @ExclusionCriteria  VALUES
('Test1'), ('Test2'),('Another string'),('Test string 4')
DECLARE @TestValue NVARCHAR(100)
SET @TestValue = 'Test1 but with some more text on the end'
--  If you want to compare with the first word in the Test Value only
--  CHARINDEX here will look for the first space, returns the position
--  The position returned then will be used by the LEFT function to get the first word.
--  I substracted 1 from the position returned to excluded the space itself.
SELECT  *
FROM    @ExclusionCriteria 
WHERE   Criteria  = LEFT(@TestValue, CHARINDEX(' ', @TestValue)-1)
--  If you want to compare any part of the TestValue
--  CHARINDEX here will look the Criteria as part of the TestValue. 
--  If exists, then will return the position, which will be greater than zero.
SELECT  *
FROM    @ExclusionCriteria 
WHERE   CHARINDEX(Criteria, @TestValue) > 0

SET @TestValue = 'Test1 but with some another string'
SELECT  *
FROM    @ExclusionCriteria 
WHERE   Criteria  = LEFT(@TestValue, CHARINDEX(' ', @TestValue)-1)
SELECT  *
FROM    @ExclusionCriteria 
WHERE   CHARINDEX(Criteria, @TestValue) > 0

相关内容

最新更新