表格:l_test1
CREATE TABLE l_test1
(
Cola VARCHAR(10)
);
表格:
l_test2
CREATE TABLE l_test2
(
Cola VARCHAR(20)
);
插入:
INSERT INTO l_test1 VALUES('1');
INSERT INTO l_test1 VALUES('12');
INSERT INTO l_test1 VALUES('123');
INSERT INTO l_test1 VALUES('1234');
INSERT INTO l_test2 VALUES('991234567890');
INSERT INTO l_test2 VALUES('9912345678901');
INSERT INTO l_test2 VALUES('99123456789012');
INSERT INTO l_test2 VALUES('123991234567890');
INSERT INTO l_test2 VALUES('981234567890');
INSERT INTO l_test2 VALUES('1234991234567890');
INSERT INTO l_test2 VALUES('1981234567890');
注意:现在,我要删除与数字匹配的表
l_test2
的开始和结束数字存在于表
l_test1
中。例如:在上表中,我在表
1,12,123,1234
中具有l_test1
值。现在我要删除与这些数字匹配的表
l_test2
的值。第二条记录表
l_test2
与表1
中的值l_test1
匹配,因此应将其删除。更新所有值后,表
l_test2
应如下所示:预期结果:
Cola
---------------------------
991234567890
991234567890
991234567890
991234567890
981234567890
991234567890
981234567890
最佳答案
使用STUFF
:
LiveDemo
WITH cte1 AS
(
SELECT t2.Cola, MAX(t1.Cola) AS r
FROM #l_test2 t2
JOIN #l_test1 t1
ON t2.Cola LIKE t1.Cola + '%'
GROUP BY t2.Cola
),
cte2 AS
(
SELECT t2.Cola, MAX(t1.Cola) AS r
FROM #l_test2 t2
JOIN #l_test1 t1
ON t2.Cola LIKE '%' + t1.Cola
GROUP BY t2.Cola
), cte3 AS
(
SELECT Cola, STUFF(Cola, 1, LEN(r), '') AS sanitized
FROM cte1
UNION ALL
SELECT Cola, STUFF(Cola, LEN(Cola) - LEN(r) + 1, LEN(r), '') AS sanitized
FROM cte2
)
SELECT sanitized
FROM cte3
UNION ALL
SELECT Cola
FROM #l_test2 t
WHERE NOT EXISTS (SELECT 1 FROM cte3 c3 WHERE c3.Cola = t.Cola);
为了便于阅读,我将其分为几部分:
cte1-删除前缀
cte2-删除后缀
cte3-结合消毒
最终-获取未消毒的行
随意将我的解决方案组合成更简洁的方式;)
关于sql - SQL Server 2008 R2:更新与另一个表匹配的表值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33014985/