我有两张桌子:
目标表:Specialisation (id , name , description)
来源表TempSpecialisation(id , name , description)
如果名称匹配,我想将TempSpe.description
复制到Specialisation.Description
,或在Specialisation
中插入所有列的新记录。
由于Specialisation.name
末尾有空格,我得到重复的条目。
我的程序是:
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
表专业化
id Name Descriptions
545454 "Allergist " null
表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
答案 0 :(得分:3)
使用LTRIM(RTRIM(s.Name))
从字段的开头和结尾删除空格,以便合并语句变为:
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
答案 1 :(得分:0)
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
答案 2 :(得分:0)
我用过
ON CHARINDEX(s.name,t.name) = 1
现在正在工作!! 谢谢