SQL Server guide

Upsert an organization


Creates a new organization or updates an existing one. This example demonstrates using the UPSERT INTO statement, identifying the organization by ID or external ID.

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 Organizations
(
	 name
	--id or external_id can be supplied for UPSERT
	,id 
	--or--
	,external_id
	 
	,group_id 
	,tags
	,details
	,notes
	,organization_fields
	,domain_names
	,shared_tickets
	,shared_comments
)
VALUES(
	'Abc Inc'
	,1234567 --id
	--or--
	,'zcrm_1558554000052161270'  --external_id
	
	,114094762733  
	,'["paid","trial","solved"]' 
	,'some details'
	,'some notes'
	,'{"startdate": "1981-01-23", "revenue": 12000000.50, "somenumber": 1235678}'
	,'["aaa.com", "bbb.com"]'
	,'false'
	,'false'
)

Using OPENQUERY in SQL Server

SELECT * FROM OPENQUERY([LS_TO_ZENDESK_IN_GATEWAY], 'UPSERT INTO Organizations
(
	 name
	--id or external_id can be supplied for UPSERT
	,id 
	--or--
	,external_id
	 
	,group_id 
	,tags
	,details
	,notes
	,organization_fields
	,domain_names
	,shared_tickets
	,shared_comments
)
VALUES(
	''Abc Inc''
	,1234567 --id
	--or--
	,''zcrm_1558554000052161270''  --external_id
	
	,114094762733  
	,''["paid","trial","solved"]'' 
	,''some details''
	,''some notes''
	,''{"startdate": "1981-01-23", "revenue": 12000000.50, "somenumber": 1235678}''
	,''["aaa.com", "bbb.com"]''
	,''false''
	,''false''
)')

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_ZENDESK_IN_GATEWAY] syntax.

DECLARE @MyQuery NVARCHAR(MAX) = 'UPSERT INTO Organizations
(
	 name
	--id or external_id can be supplied for UPSERT
	,id 
	--or--
	,external_id
	 
	,group_id 
	,tags
	,details
	,notes
	,organization_fields
	,domain_names
	,shared_tickets
	,shared_comments
)
VALUES(
	''Abc Inc''
	,1234567 --id
	--or--
	,''zcrm_1558554000052161270''  --external_id
	
	,114094762733  
	,''["paid","trial","solved"]'' 
	,''some details''
	,''some notes''
	,''{"startdate": "1981-01-23", "revenue": 12000000.50, "somenumber": 1235678}''
	,''["aaa.com", "bbb.com"]''
	,''false''
	,''false''
)'
EXEC (@MyQuery) AT [LS_TO_ZENDESK_IN_GATEWAY]