具有多行选择的从属插入

时间:2017-10-17 08:45:37

标签: sql sql-server select insert bulkinsert

我们有一个使用SQL Server的CRM系统,并希望用电子邮件地址填充所有客户,即使该电子邮件地址为NULL。

有一个Customer表,一个电子邮件地址表和一个Linker表。

我可以为需要新电子邮件行的所有客户执行SELECT查询:

SELECT @CompanyId = Comp_CompanyId
FROM Company
WHERE Company.Comp_CompanyId NOT IN (
  SELECT ELink_RecordID
  FROM EmailLink
)

我可以执行INSERT语句向客户添加电子邮件地址:

DECLARE @EmailId int
DECLARE @ELinkId int

EXEC @ELinkId = eware_get_identity_id 'Email'
EXEC @EmailId = eware_get_identity_id 'Email'

INSERT INTO Email (
  Emai_EmailId,
  Emai_CreatedBy,
  Emai_CreatedDate,
  Emai_UpdatedBy,
  Emai_UpdatedDate,
  Emai_TimeStamp,
  Emai_EmailAddress
)
VALUES (
  @EmailId,
  1,
  GETDATE(),
  1,
  GETDATE(),
  GETDATE(),
  NULL
)
INSERT INTO EmailLink(
  ELink_LinkID,
  ELink_CreatedBy,
  ELink_CreatedDate,
  ELink_UpdatedBy,
  ELink_UpdatedDate,
  ELink_TimeStamp,
  ELink_EntityID,
  ELink_RecordID,
  ELink_Type,
  ELink_EmailId
)
VALUES(
  @ELinkId,
  1,
  GETDATE(),
  1,
  GETDATE(),
  GETDATE(),
  5,          -- Person is 13, Company is 5
  COMPANY_ID_GOES_HERE,
  'Business',
  @EmailId
)

有没有办法可以将这些组合成一个大的SQL语句而无需使用外部工具?我可以编写一个快速的Python程序来执行此操作,但维护此长期的人员是以SQL为重点的。

我得到的最远的是将SELECTINSERT组合成电子邮件,但无法确定如何INSERT链接器行:

DECLARE @CompanyId int
DECLARE @EmailId int
DECLARE @ELinkId int

EXEC @ELinkId = eware_get_identity_id 'Email'
EXEC @EmailId = eware_get_identity_id 'Email'

INSERT INTO Email (
  Emai_EmailId,
  Emai_CreatedBy,
  Emai_CreatedDate,
  Emai_UpdatedBy,
  Emai_UpdatedDate,
  Emai_TimeStamp,
  Emai_EmailAddress
)
VALUES (
  @EmailId,
  1,
  GETDATE(),
  1,
  GETDATE(),
  GETDATE(),
  NULL
)

SELECT @CompanyId = Comp_CompanyId
FROM Company
WHERE Company.Comp_CompanyId NOT IN (
  SELECT ELink_RecordID
  FROM EmailLink
)

1 个答案:

答案 0 :(得分:2)

这是否适用于第二部分?

DECLARE @CompanyId int
DECLARE @EmailId int
DECLARE @ELinkId int

EXEC @ELinkId = eware_get_identity_id 'Email'
EXEC @EmailId = eware_get_identity_id 'Email'

INSERT INTO Email (
  Emai_EmailId,
  Emai_CreatedBy,
  Emai_CreatedDate,
  Emai_UpdatedBy,
  Emai_UpdatedDate,
  Emai_TimeStamp,
  Emai_EmailAddress
)
VALUES (
  @EmailId,
  1,
  GETDATE(),
  1,
  GETDATE(),
  GETDATE(),
  NULL
)
;WITH cteX
AS(
    SELECT CompanyId = Comp_CompanyId
    FROM Company
    WHERE Company.Comp_CompanyId 
    NOT IN (
            SELECT ELink_RecordID
            FROM EmailLink 
            )
)
INSERT INTO EmailLink(
  ELink_LinkID,
  ELink_CreatedBy,
  ELink_CreatedDate,
  ELink_UpdatedBy,
  ELink_UpdatedDate,
  ELink_TimeStamp,
  ELink_EntityID,
  ELink_RecordID,
  ELink_Type,
  ELink_EmailId
)
SELECT 
    @ELinkId,
    1,
    GETDATE(),
    1,
    GETDATE(),
    GETDATE(),
    5,          -- Person is 13, Company is 5
    X.CompanyId, --COMPANY_ID_GOES_HERE,
    'Business',
    @EmailId
FROM 
    cteX X