如何 Trim 存储过程中字符串的空格?

How to Trim white spaces of string in stored procedure?

我有两个 table:

目标table:Specialisation (id , name , description)

来源tableTempSpecialisation(id , name , description)

如果名称匹配,我想将 TempSpe.description 复制到 Specialisation.Description,或者在 Specialisation 中插入一条包含所有列的新记录。 由于 Specialisation.name.

末尾的白色 space,我得到了重复的条目

我的程序是:

USE [TempDatabase]
GO
/****** Object:  StoredProcedure [dbo].[TempDatabase2]    Script Date:      23/12/2015 3:46:49 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[TempDatabase2]
WITH EXECUTE AS owner
as
BEGIN 

MERGE Specialisation as T
USING TempSpecialisation as S
ON s.Name = T.Name
WHEN NOT MATCHED BY Target 
THEN INSERT(id ,Name, Description1) VALUES(S.id ,S.Name, S.Description1)
WHEN MATCHED and t.name =s.name
THEN UPDATE SET T.Description1 = S.Description1 
OUTPUT $action, inserted.*;
End

Table 专业化

id       Name           Descriptions
545454   "Allergist  "  null

Table TEmpSpecialisation

id       Name         Descriptions
1        "Allergist"  This is a doctor who helps with allergies. 

我需要从 TEmpSpecialisation 更新专业化描述。 但它给出的输出类似于

id       Name           Descriptions  
1        "Allergist"    This is a doctor who helps with allergies. 
545454   "Allergist  "  null

使用LTRIM(RTRIM(s.Name))去掉字段开头和结尾的白色space,所以你的合并语句变成:

MERGE Specialisation as T
USING TempSpecialisation as S
ON LTRIM(RTRIM(s.Name)) = LTRIM(RTRIM(T.Name))
WHEN NOT MATCHED BY Target 
THEN INSERT(id ,Name, Description1) VALUES(S.id ,S.Name, S.Description1)
WHEN MATCHED
THEN UPDATE SET T.Description1 = S.Description1 
OUTPUT $action, inserted.*;
End

LTRIM Documentation

RTRIM Documentation

ALTER PROCEDURE [dbo].[TempDatabase2]
WITH EXECUTE AS OWNER
AS
BEGIN

    MERGE dbo.Specialisation T
    USING dbo.TempSpecialisation S ON LTRIM(S.Name) = LTRIM(T.Name)
    WHEN NOT MATCHED BY TARGET
        THEN
            INSERT (id, Name, Description1)
            VALUES (S.id, S.Name, S.Description1)
    WHEN MATCHED AND ISNULL(T.Description1, '') != ISNULL(S.Description1, '') -- remove ISNULL if Description1 NOT NULL
        THEN
            UPDATE SET T.Description1 = S.Description1
    OUTPUT $ACTION, INSERTED.*;

END

我用过

ON CHARINDEX(s.name,t.name) = 1 

现在可以使用了!! 谢谢