SQL Server 使用SQL删除部分服务器名称

umuewwlo  于 2023-01-25  发布在  其他
关注(0)|答案(2)|浏览(197)

我有一个表,其中有一堆不同的服务器,大多数都被列为 servername.ad.edu。我想删除第一个点之后的所有内容。所以它在我的表中只显示为 servername。提供给我的用于填充表的代码不是我写的,但我确实添加了 LEFT 语句,看看我是否可以在填充过程中删除它。以下是我的代码...

DELETE FROM clean_tanium_server;
MERGE clean_tanium_server AS Target
USING tanium_server AS Source
ON Source.computer_id = Target.computer_id AND Source.[ci_installed_application name] = Target.application_name
WHEN NOT MATCHED BY Target THEN
    INSERT (computer_id, computer_name, operating_system, application_name, application_normalized_name, chassis_type, cpu_core, cpu_processor, ip_address)
    VALUES (Source.computer_id, Source.computer_name, Source.operating_system, Source.[ci_installed_application name], Source.[ci_installed_application normalized_name], Source.chassis_type, Source.cpu_core, Source.cpu_processor, Source.ip_address)
WHEN MATCHED THEN UPDATE SET
    *Target.computer_name = LEFT(Source.computer_name, CHARINDEX('.', Source.computer_name) - 1),*
    Target.operating_system = Source.operating_system,
    Target.application_normalized_name = Source.[ci_installed_application normalized_name]
WHEN NOT MATCHED BY Source THEN
    DELETE;

所以我不明白为什么当我填充表的时候,他们没有省略.ad.edu部分。任何帮助都是非常感谢的。谢谢。
当前外观:

computer_name
servername1.ad.edu
servername2.ad.edu
servername3.us.edu

我希望它看起来如何:

computer_name
servername1
servername2
servername3
yqyhoc1h

yqyhoc1h1#

当进入WHENMATCHEDTHENUPDATESET块时,您只应用LEFT修改,但是正如注解中指出的,您首先清空了表,所以您永远不会匹配,并且将只执行WHENNOTMATCHEDBYTargetTHEN块,该块没有您的LEFT修改

wvt8vs2t

wvt8vs2t2#

以下是其他答复和评论的摘要。
1.因为您首先删除表中的所有行,所以不需要MERGE语句,因此只需要INSERT
1.我建议使用TRUNCATE而不是DELETE来删除所有行-除非您有特殊需要。Pros and Cons of Truncate over Delete
1.在INSERT语句中,使用Aaron Bertrand提供的代码去掉计算机名末尾。

TRUNCATE TABLE clean_tanium_server;

INSERT INTO clean_tanium_server (
    computer_id
    , computer_name
    , operating_system
    , application_name
    , application_normalized_name
    , chassis_type
    , cpu_core, cpu_processor
    , ip_address)
SELECT
    computer_id
    , LEFT(computer_name, CHARINDEX('.', computer_name + '.') - 1)
    , operating_system
    , [ci_installed_application name]
    , [ci_installed_application normalized_name]
    , chassis_type
    , cpu_core
    , cpu_processor
    , ip_address
FROM tanium_server;

相关问题