我的表table_1的数据如下:
| WordID| Add |
+-------+------+
| 1 | Hello|
| 2 | Hi |
| 3 | Go |
| 4 | Come |
我有一个字符串“你好,请到约翰家。”
我想删除问候并使用SQL Server从字符串中查找,输出结果应为
", Please to John's House"
我该怎么办?
答案 0 :(得分:1)
我正在使用克里斯莫里斯(Chris Morris)创建的函数,该函数由Dwain Camps在here中进行了解释。
我更改了字符串以测试误报。
declare @list varchar(255) = 'Hello, Please Go to Phillip''s House who left long ago.';
create table table_1(WordID int, [Add] varchar(255));
insert into table_1(WordID, [Add]) values
(1, 'Hello'),
(2, 'Hi'),
(3, 'Go'),
(4, 'Come');
SELECT ( SELECT Item + ''
FROM dbo.PatternSplitCM(@list, '%[^a-zA-Z'']%') ps
WHERE NOT EXISTS( SELECT * FROM table_1 t WHERE ps.Item = t.[Add])
ORDER BY ItemNumber
FOR XML PATH(''), TYPE).value('./text()[1]', 'varchar(max)')
函数定义在这里:
-- PatternSplitCM will split a string based on a pattern of the form
-- supported by LIKE and PATINDEX
--
-- Created by: Chris Morris 12-Oct-2012
CREATE FUNCTION [dbo].[PatternSplitCM]
(
@List VARCHAR(8000) = NULL
,@Pattern VARCHAR(50)
) RETURNS TABLE WITH SCHEMABINDING
AS
RETURN
WITH numbers AS (
SELECT TOP(ISNULL(DATALENGTH(@List), 0))
n = ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
FROM
(VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) d (n),
(VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) e (n),
(VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) f (n),
(VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) g (n))
SELECT
ItemNumber = ROW_NUMBER() OVER(ORDER BY MIN(n)),
Item = SUBSTRING(@List,MIN(n),1+MAX(n)-MIN(n)),
[Matched]
FROM (
SELECT n, y.[Matched], Grouper = n - ROW_NUMBER() OVER(ORDER BY y.[Matched],n)
FROM numbers
CROSS APPLY (
SELECT [Matched] = CASE WHEN SUBSTRING(@List,n,1) LIKE @Pattern THEN 1 ELSE 0 END
) y
) d
GROUP BY [Matched], Grouper;
答案 1 :(得分:0)
您需要对该表进行(伪)更新:
declare @list varchar(255) = 'Hello, Please Go to John''s House.';
create table table_1(WordID int, [Add] varchar(255));
insert into table_1(WordID, [Add]) values
(1, 'Hello'),
(2, 'Hi'),
(3, 'Go'),
(4, 'Come');
update table_1
set @list = replace(@list, [Add], '');
select @list;
结果:
, Please to John's House.