SQL Server guide

Bulk upsert members from SQL Server


Subscribes or unsubscribes members in bulk using UPSERT INTO ListMembers SOURCE('MSSQL', ...). Data is read from the SQL Server database; result set column names (or aliases) must match ListMembers input columns (e.g. EmailAddress, FirstName, Status). Pass ListId in the WITH clause.

Standard SQL query example

This is the base query accepted by the connector. To execute it in SQL Server, you have to pass it to the Data Gateway via a Linked Server. See how to accomplish this using the examples below.

UPSERT INTO ListMembers
SOURCE('MSSQL', 'Data Source=localhost;Initial Catalog=tempdb;Integrated Security=true'
,'select ''brucewayne10@gmail.com'' EmailAddress,''first1'' as FirstName, ''subscribed'' Status 
UNION ALL
select ''test55@gmail.com'' EmailAddress,''first1'' FirstName, ''subscribed'' Status 
')
WITH(ListId='a4d24015f8')

 --//column name alias must match with InputColumns of ListMembers

Using OPENQUERY in SQL Server

SELECT * FROM OPENQUERY([LS_TO_MAILCHIMP_IN_GATEWAY], 'UPSERT INTO ListMembers
SOURCE(''MSSQL'', ''Data Source=localhost;Initial Catalog=tempdb;Integrated Security=true''
,''select ''''brucewayne10@gmail.com'''' EmailAddress,''''first1'''' as FirstName, ''''subscribed'''' Status 
UNION ALL
select ''''test55@gmail.com'''' EmailAddress,''''first1'''' FirstName, ''''subscribed'''' Status 
'')
WITH(ListId=''a4d24015f8'')

 --//column name alias must match with InputColumns of ListMembers')

Using EXEC in SQL Server (handling larger SQL text)

The major drawback of OPENQUERY is its inability to incorporate variables within SQL statements. This often leads to the use of cumbersome dynamic SQL (with numerous ticks and escape characters).

Fortunately, starting with SQL 2005 and onwards, you can utilize the EXEC (your_sql) AT [LS_TO_MAILCHIMP_IN_GATEWAY] syntax.

DECLARE @MyQuery NVARCHAR(MAX) = 'UPSERT INTO ListMembers
SOURCE(''MSSQL'', ''Data Source=localhost;Initial Catalog=tempdb;Integrated Security=true''
,''select ''''brucewayne10@gmail.com'''' EmailAddress,''''first1'''' as FirstName, ''''subscribed'''' Status 
UNION ALL
select ''''test55@gmail.com'''' EmailAddress,''''first1'''' FirstName, ''''subscribed'''' Status 
'')
WITH(ListId=''a4d24015f8'')

 --//column name alias must match with InputColumns of ListMembers'
EXEC (@MyQuery) AT [LS_TO_MAILCHIMP_IN_GATEWAY]