如何在SQL中使用通用模式更改句子

时间:2017-04-07 15:52:33

标签: sql sql-server tsql

Alexa,谢谢您访问芝加哥!我们希望您尽快回来!
Katana,感谢您访问达拉斯!我们希望您尽快回来!星期日,谢谢您访问纽约市!我们希望你很快回来! 比克斯比,谢谢你来西雅图!我们希望您能尽快回来!

假设这些是任意表中列中的值,我将如何编写一个SQL查询,将所有上述内容替换为&#34; < em>名字,感谢您访问洛杉矶!我们希望您能尽快回来!&#34;

虽然这些只有四行,但我需要编辑500多个。

我正在使用T-SQL / SSMS。

5 个答案:

答案 0 :(得分:2)

我不知道这与REPLACE()有什么关系。我会把它写成:

update t
    set col = 'Thank you for visiting Los Angeles!'
    where col in ('Thank you for visiting Chicago!',
                  'Thank you for visiting Dallas!',
                  'Thank you for visiting New York City!',
                  'Thank you for visiting Seattle!'
                 );

答案 1 :(得分:0)

这将有效:

update t
    set col =
        select left(col,charindex('visiting',col,1)+8) + 'Los Angelese!'

答案 2 :(得分:0)

CREATE TABLE #StackTest
(
    Sentence varchar(50)
)

INSERT INTO #StackTest
        ( Sentence )
VALUES
('Alexa, thank you for visiting Los Angeles!'),
('Katana, thank you for visiting Chicago!'),
('Siri, thank you for visiting Dallas!'),
('Bixby, thank you for visiting New York City!')

SELECT
    'First Name' + SUBSTRING(Sentence, CHARINDEX(',', Sentence, 1), LEN(Sentence) - CHARINDEX(',', Sentence, 1))
FROM
    #StackTest

DROP TABLE #StackTest

答案 3 :(得分:0)

使用CharIndexSubstring

DECLARE @SampleData AS TABLE (Value varchar(200))

INSERT INTO @SampleData
VALUES ('Alexa, thank you for visiting Chicago! We hope you come back soon!'),
('Katana, thank you for visiting Dallas! We hope you come back soon!'),
('Siri, thank you for visiting New York City! We hope you come back soon!'),
('Bixby, thank you for visiting Seattle! We hope you come back soon!')

SELECT 'First Name' + SUBSTRING(sd.[Value], CHARINDEX(',', sd.[Value], 1), len(sd.[Value]) - CHARINDEX(',', sd.[Value], 1) + 1)
FROM @SampleData sd

链接演示:Rextester

答案 4 :(得分:0)

使用东西可能是最简单的方法:

创建并填充样本表(在将来的问题中保存此步骤)

DECLARE @sampleData as TABLE
(
    sentence varchar(100)
)

INSERT INTO @SampleData VALUES
('Alexa, thank you for visiting Chicago! We hope you come back soon!'),
('Katana, thank you for visiting Dallas! We hope you come back soon!'),
('Siri, thank you for visiting New York City! We hope you come back soon!'),
('Bixby, thank you for visiting Seattle! We hope you come back soon!')

更新声明:

UPDATE @sampleData 
SET sentence = STUFF(sentence, 
                     charindex(',', sentence), 
                     len(sentence), 
                     ', thank you for visiting Los Angeles! We hope you come back soon!')

测试:

SELECT *
FROM @sampleData 
WHERE sentence LIKE '%, thank you for visiting %! We hope you come back soon!'

结果:

sentence
Alexa, thank you for visiting Los Angeles! We hope you come back soon!
Katana, thank you for visiting Los Angeles! We hope you come back soon!
Siri, thank you for visiting Los Angeles! We hope you come back soon!
Bixby, thank you for visiting Los Angeles! We hope you come back soon!

See a live demo on rextester.