发布后,
TSQL Variable With List of Values for IN Clause
我形成了varchar的表变量,例如
Declare @myList_1(Id varchar(2))
Insert into @myList_1
Select id from (VALUES ('x1')) AS tbl(id)
Insert into @myList_1
Select id from (VALUES ('x2')) AS tbl(id)
Insert into @myList_1
Select id from (VALUES ('x3')) AS tbl(id)
但是,我需要扩展这个概念,以便我可以做一些像“比较”这样的事情
e.g:
myTable.myCol like ('%' + @myList_1 + '%')
以上:SSMS 2008 r2给出错误:'必须声明标量变量@ myList_1'
如果可能的话,我想在没有迭代器或循环结构的情况下这样做......
答案 0 :(得分:1)
让我们假设遵循测试数据和表格结构。
-- Create test table
CREATE TABLE [dbo].[myTable](
[Id] [int] NOT NULL PRIMARY KEY,
[myCol] [varchar](100) NULL)
GO
-- Insert test data
INSERT INTO myTable(Id, myCol)
VALUES (1, 'Bladder cancer'),
(2, 'Lung cancer'),
(3, 'Brain cancer'),
(4, 'Melanoma'),
(5, 'Breast cancer'),
(6, 'Non-Hodgkin lymphoma'),
(7, 'Cervical cancer'),
(8, 'Ovarian cancer'),
(9, 'Cardiovascular disease'),
(10, 'Nerve damage'),
(11, 'Kidney damage'),
(12, 'Eye damage'),
(13, 'Foot damage'),
(14, 'Skin conditions'),
(15, 'Alzheimer''s disease'),
(16, 'Hearing impairment')
GO
现在实际的SQL将基于使用表变量@ myList_1
加入要搜索的表。-- Create list of items to look for
Declare @myList_1 table(Id varchar(20))
Insert into @myList_1
Select id from (VALUES ('cancer')) AS tbl(id)
Insert into @myList_1
Select id from (VALUES ('Melanoma')) AS tbl(id)
Insert into @myList_1
Select id from (VALUES ('lymphoma')) AS tbl(id)
-- Do query
SELECT myTable.Id, myTable.myCol
FROM myTable
JOIN @myList_1 as ItemsList
ON myTable.myCol like '%' + ItemsList.Id + '%'
在myCol
只能匹配@myList_1
中的单个值的简单情况下,这应该足够了,但对于myCol
可能匹配{{1}中的多个值的情况您应该将@myList_1
添加到查询
DISTINCT