如何使用 tSQL 匹配和删除字符串后的所有内容? [英] How to use tSQL to match and remove everything after a string?

查看:23
本文介绍了如何使用 tSQL 匹配和删除字符串后的所有内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 tSQL 查找字符串,如果存在,则返回该字符串之前的所有内容?

How can I use tSQL to find a string, and if it exists, return everything before that string?

即在下面的示例中,在 ETL 过程中,我们如何从源中获取列,识别字符串 ?uniquecode= 并因此在接收器列的 SELECT 语句中删除该字符串及其后的所有内容?

i.e. in the example below, in an ETL process, how would we take the column from source, identify the string ?uniquecode= and therefore remove that, and everything else after it, in the SELECT statement for the sink column?

我怎样才能最好地修改下面的这个 tSQL 语句以返回上面 SinkPageURL 列中的值?

How can I best modify this tSQL statement below to return the values in SinkPageURL column above?

SELECT SourcePageURL FROM ExampleTable

我在这里尝试了一个小提琴 - http://sqlfiddle.com/#!18/3b60a/4 使用以下语句.它忽略了 '?uniquecode=' 不存在的值,并且还留下了 '?'象征.需要它与 MS SQL Server '17 一起使用.

I have attempted a Fiddle here - http://sqlfiddle.com/#!18/3b60a/4 using the below statement. It is disregarding the values where '?uniquecode=' does not exist though, and also leaves the '?' symbol. Need this to work with MS SQL Server '17.

有点接近,但没有雪茄.感谢帮助!

Somewhat close, but no cigar. Help appreciated!

SELECT LEFT(SourcePageURL, CHARINDEX('?uniquecode=', SourcePageURL)) FROM sql_test

推荐答案

试试这个查询:

SELECT
    CASE WHEN CHARINDEX('?uniquecode=', SourcePageURL) > 0
         THEN SUBSTRING(SourcePageURL,
                        1,
                        CHARINDEX('?uniquecode=', SourcePageURL) - 1)
         ELSE SourcePageURL END AS new_source
FROM sql_test;

如果您想使用此逻辑更新示例中的源网址,您可以尝试以下操作:

If you instead wanted to update the source URLs in your example using this logic, you could try the following:

UPDATE sql_test
SET SourcePageURL = SUBSTRING(SourcePageURL,
                        1,
                        CHARINDEX('?uniquecode=', SourcePageURL) - 1)
WHERE SourcePageURL LIKE '%?uniquecode=%';

这篇关于如何使用 tSQL 匹配和删除字符串后的所有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆