在 SQL 中用逗号分割字符串并将它们存储为 split_item1、split_item2 和
select column_name from table-name where column_name = 'split_item1' or split_item2'
请为此发布正确的语法
假设您正在使用SQL Server
,您需要,
从列的两侧连接,以便您可以匹配您正在搜索的值。
SELECT *
FROM TableName
WHERE ',' + csvColumn + ',' LIKE '%,' + 'split_item1' + ',%' OR
',' + csvColumn + ',' LIKE '%,' + 'split_item2' + ',%'
CONCAT()
对于 MySQL,||
对于 Oracle ,每个 dbms 的连接符号都不同。
您可以使用以下代码(为 sqlserver 创建)。
Create Function FUN_STRING_SPLIT(@text varchar(max), @separator varchar(10))
Returns @Result Table
(
POSITION INT IDENTITY(1,1) NOT NULL, VALUE VARCHAR(max)
)
As
Begin
Declare @ini int = 1, @end int = 0
While @end <= LEN(@text)
Begin
if @end > 0 set @ini = @end + LEN(@separator)
if @ini > 0 set @end = CHARINDEX(@separator, @text, @ini)
if @end = 0 set @end = LEN(@text) + 1
Insert Into @Result (VALUE) Values (SUBSTRING(@text,@ini,@end - @ini))
End
Return
End
然后像这样使用:
Select * From FUN_STRING_SPLIT('Word1,Word2,Word2,Etc..', ',');
select * from fromSplitStringSep('Word1 wordr2 word3',' ')
CREATE function [dbo].[SplitStringSep]
(
@str nvarchar(4000),
@separator char(1)
)
returns table
AS
return (
with tokens(p, a, b) AS (
select
1,
1,
charindex(@separator, @str)
union all
select
p + 1,
b + 1,
charindex(@separator, @str, b + 1)
from tokens
where b > 0
)
select
p-1 zeroBasedOccurance,
substring(
@str,
a,
case when b > 0 then b-a ELSE 4000 end)
AS s
from tokens
)