SQL Server guide

Query data (Simple Mode) using #DirectSQL


Returns report data using GAQL in simple mode. Prefix the query with #DirectSQL and write the GAQL SELECT directly; use the Query Builder to pick fields and paste the query below.

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.

#DirectSQL 

--Use Query Builder here https://developers.google.com/google-ads/api/fields/v18/overview_query_builder
--Paste Generated query below
				
SELECT  campaign.id, campaign.name, metrics.impressions, metrics.clicks, metrics.cost_micros
FROM campaign 
--WHERE campaign.status = 'ENABLED'
--ORDER BY campaign.id
--LIMIT 1000

Using OPENQUERY in SQL Server

SELECT * FROM OPENQUERY([LS_TO_GOOGLE_ADS_IN_GATEWAY], '#DirectSQL 

--Use Query Builder here https://developers.google.com/google-ads/api/fields/v18/overview_query_builder
--Paste Generated query below
				
SELECT  campaign.id, campaign.name, metrics.impressions, metrics.clicks, metrics.cost_micros
FROM campaign 
--WHERE campaign.status = ''ENABLED''
--ORDER BY campaign.id
--LIMIT 1000')

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

DECLARE @MyQuery NVARCHAR(MAX) = '#DirectSQL 

--Use Query Builder here https://developers.google.com/google-ads/api/fields/v18/overview_query_builder
--Paste Generated query below
				
SELECT  campaign.id, campaign.name, metrics.impressions, metrics.clicks, metrics.cost_micros
FROM campaign 
--WHERE campaign.status = ''ENABLED''
--ORDER BY campaign.id
--LIMIT 1000'
EXEC (@MyQuery) AT [LS_TO_GOOGLE_ADS_IN_GATEWAY]