Home > database >  O a SQL statements involving delimited string
O a SQL statements involving delimited string

Time:10-03

Inside a field formed comma connection string
Table t1

Id values text

Content of 1, 2, 1,,,
1, 2,,
Content of 2, 4, 3,,
April 6,,,

Table t2 is a field id

Id

1
2
3

Now want to query the t1 values in the field with a comma separated string has a satisfied t2 is eligible
Such as t1, the former three are satisfy conditions


CodePudding user response:

The test data
 -If not object_id (N 'Tempdb for.. # T1 ') is null 
# drop table T1
Go
# the Create table T1 (int [id], [values] nvarchar (23), [text] nvarchar (25))
Insert # T1
Select 1, N '1, 2', N 'content,,,' union all
Select 2, N '1', N 'content,,,' union all
Select 3, N '2, 4', N 'content,,,' union all
Select 4, N '6', N 'content,,,
GO
If not object_id (N 'Tempdb for.. # T2 ') is null
Drop table # T2
Go
The Create table # T2 (int [id])
Insert # T2
Union all select 1
Union all select 2
Select 3
Go
- the end of the test data
SELECT DISTINCT # T1. *
The FROM # T1
The JOIN # T2
ON CHARINDEX (', '+ RTRIM (# T2. Id) +', ', ', '+ [values] +', ') & gt; 0;


  • Related