<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>CSV File / REST API Driver Archives | ZappySys Blog</title>
	<atom:link href="https://zappysys.com/blog/category/odbc-powerpack/odbc-drivers/csv-rest-api-driver/feed/" rel="self" type="application/rss+xml" />
	<link>https://zappysys.com/blog/category/odbc-powerpack/odbc-drivers/csv-rest-api-driver/</link>
	<description>SSIS / ODBC Drivers / API Connectors for JSON, XML, Azure, Amazon AWS, Salesforce, MongoDB and more</description>
	<lastBuildDate>Wed, 11 Mar 2026 07:08:29 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.4.4</generator>

<image>
	<url>https://zappysys.com/blog/wp-content/uploads/2023/01/cropped-zappysys-symbol-large-32x32.png</url>
	<title>CSV File / REST API Driver Archives | ZappySys Blog</title>
	<link>https://zappysys.com/blog/category/odbc-powerpack/odbc-drivers/csv-rest-api-driver/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to import Amazon MWS data into SQL Server (T-SQL)</title>
		<link>https://zappysys.com/blog/import-amazon-mws-data-sql-server-t-sql/</link>
		
		<dc:creator><![CDATA[ZappySys]]></dc:creator>
		<pubDate>Thu, 30 May 2019 15:37:37 +0000</pubDate>
				<category><![CDATA[CSV File / REST API Driver]]></category>
		<category><![CDATA[ODBC Gateway]]></category>
		<category><![CDATA[T-SQL (SQL Server)]]></category>
		<category><![CDATA[XML File / SOAP API Driver]]></category>
		<category><![CDATA[Amazon MWS]]></category>
		<category><![CDATA[linked server]]></category>
		<category><![CDATA[openquery]]></category>
		<category><![CDATA[t-sql]]></category>
		<guid isPermaLink="false">https://zappysys.com/blog/?p=6961</guid>

					<description><![CDATA[<p>Introduction In our previous blog post we saw how to import rest API in SQL Server. Using same concepts lets look at how to import Amazon MWS Data into SQL Server. We will explore many techniques to call Amazon MWS API and learn how to automate Amazon MWS data extraction without doing any ETL. We [&#8230;]</p>
<p>The post <a href="https://zappysys.com/blog/import-amazon-mws-data-sql-server-t-sql/">How to import Amazon MWS data into SQL Server (T-SQL)</a> appeared first on <a href="https://zappysys.com/blog">ZappySys Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<div class="su-note"  style="border-color:#e2dec9;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;"><div class="su-note-inner su-u-clearfix su-u-trim" style="background-color:#fcf8e3;border-color:#ffffff;color:#8a6d3b;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;">
<strong><span style="vertical-align: text-bottom;font-size: 0.86em;">⚠️</span> Deprecation Notice: MWS API is deprecated</strong><br />
Amazon&#8217;s MWS (Marketplace Web Service) is being deprecated and <strong>replaced by the newer AWS Selling Partner API (SP-API).</strong> For a more robust and secure integration, we <strong>recommend</strong> using our <strong><a href="/api/integration-hub/amazon-selling-partner-connector/">AWS Selling Partner (SP-API) Connector</a>.</strong> As Amazon is phasing out MWS functionality and eventually plans to fully deprecate it.<br />
</div></div>
<p><a href="https://zappysys.com/blog/wp-content/uploads/2016/10/amazon-mws-api-integration.png"><img decoding="async" class="wp-image-1632 alignleft" src="https://zappysys.com/blog/wp-content/uploads/2016/10/amazon-mws-api-integration.png" alt="" width="98" height="98" srcset="https://zappysys.com/blog/wp-content/uploads/2016/10/amazon-mws-api-integration.png 505w, https://zappysys.com/blog/wp-content/uploads/2016/10/amazon-mws-api-integration-150x150.png 150w, https://zappysys.com/blog/wp-content/uploads/2016/10/amazon-mws-api-integration-300x300.png 300w" sizes="(max-width: 98px) 100vw, 98px" /></a>In our previous blog post we saw how to <a href="https://zappysys.com/blog/import-rest-api-json-sql-server/" target="_blank" rel="noopener">import rest API in SQL Server</a>. Using same concepts lets look at how to import Amazon MWS Data into SQL Server. We will explore many techniques to call Amazon MWS API and learn how to automate Amazon MWS data extraction without doing any ETL. We will call MWS XML or CSV API just using T-SQL code. We will also learn how to Download Reports from by calling MWS API.</p>
<p>You can also refer other articles <a href="https://zappysys.com/blog/import-amazon-mws-data-power-bi/" target="_blank" rel="noopener">here (Power BI)</a> and <a href="https://zappysys.com/blog/call-amazon-mws-api-using-ssis-marketplace-web-service/" target="_blank" rel="noopener">here (SSIS)</a></p>
<p>&nbsp;</p>
<div class="content_block" id="custom_post_widget-7048"><h2>Requirements</h2>
This article talks about few tools and techniques in order to load API data in SQL Server. Please make sure following prerequisites are met.
<ol>
 	<li>Download and Install <a href="https://zappysys.com/products/odbc-powerpack/" target="_blank" rel="noopener">ZappySys ODBC PowerPack</a> (This includes XML / JSON / REST API and few other drivers for SQL Server and ODBC connectivity in tools like Excel, Power BI, SSRS)</li>
 	<li>Make sure you have access to SQL Server Instance. If you cant find one still want to try what is mentioned in this article then install <a href="https://www.microsoft.com/en-us/sql-server/sql-server-editions-express" target="_blank" rel="noopener">FREE SQL Express Edition</a></li>
 	<li>Confirm that you have SSMS Installed. If you don't have then you can download <a href="https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-2017">from here</a>.</li>
</ol></div>
<h2></h2>
<h2>About Amazon MWS  API</h2>
<p>If you want to sell something on Amazon you can use their e-commerce platform with some monthly fee. You can setup your entire online store / inventory using admin interface.</p>
<p>Amazon Marketplace Web Service (Amazon MWS) is an integrated web service API that helps Amazon sellers to programmatically exchange data on listings, orders, payments, reports, and more. Using these API you can read or write data from your Seller account and integrate it inside your own Systems (e.g. Reporting / ETL / BI tools).</p>
<div class="su-note"  style="border-color:#e5de9d;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;"><div class="su-note-inner su-u-clearfix su-u-trim" style="background-color:#fff8b7;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;">NOTE: Amazon MWS may allow only certain number of requests per minute depending which API you calling so you might want to use each call wisely. We will suggest you various techniques throughout this article so you can avoid errors so read each section carefully. You can find Throttling information on API help page itself (<a href="https://docs.developer.amazonservices.com/en_IT/orders-2013-09-01/Orders_ListOrders.html" target="_blank" rel="noopener">like this one</a> see throttling section. Also <a href="https://docs.developer.amazonservices.com/en_IT/dev_guide/DG_Throttling.html">this one</a>).</div></div>
<h2>Obtain MWS API Access Key / Secret and Seller ID</h2>
<p>Very first thing to call any MWS API is to obtain Access Key, Secret Key and Seller ID (i.e. Merchant ID). To obtain this you first have to <a href="https://docs.developer.amazonservices.com/en_US/dev_guide/DG_Registering.html" target="_blank" rel="noopener">register a developer</a>.</p>
<p>Here is where to look for your Merchant ID and Key / Secret.  Here is direct link to <a href="https://sellercentral.amazon.com/gp/account-manager/home.html/ref=xx_userperms_dnav_userperms" target="_blank" rel="noopener">User Permissions</a> page.</p>
<div id="attachment_4843" style="width: 997px" class="wp-caption alignnone"><a href="https://zappysys.com/blog/wp-content/uploads/2018/09/obtain-amazon-mws-developer-aws-access-key-secret-key-sellerid.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-4843" class="size-full wp-image-4843" src="https://zappysys.com/blog/wp-content/uploads/2018/09/obtain-amazon-mws-developer-aws-access-key-secret-key-sellerid.png" alt="How to get Amazon MWS developer keys and know your Merchant ID (i.e. Seller ID)" width="987" height="422" srcset="https://zappysys.com/blog/wp-content/uploads/2018/09/obtain-amazon-mws-developer-aws-access-key-secret-key-sellerid.png 987w, https://zappysys.com/blog/wp-content/uploads/2018/09/obtain-amazon-mws-developer-aws-access-key-secret-key-sellerid-300x128.png 300w, https://zappysys.com/blog/wp-content/uploads/2018/09/obtain-amazon-mws-developer-aws-access-key-secret-key-sellerid-768x328.png 768w" sizes="(max-width: 987px) 100vw, 987px" /></a><p id="caption-attachment-4843" class="wp-caption-text">How to get Amazon MWS developer keys and know your Merchant ID (i.e. Seller ID)</p></div>
<h2>Getting Started</h2>
<p>Now let&#8217;s look at step by step instructions on how to call Amazon MWS API and then import into Power BI. In below steps we will use  <a href="https://zappysys.com/products/odbc-powerpack/" target="_blank" rel="noopener">ZappySys ODBC PowerPack</a> so make sure it&#8217;s installed first.</p>
<h3>Using ScratchPad to Test Amazon MWS API</h3>
<p>Each MWS API has set of required and optional parameters. You can refer each API page for details. For example <a href="https://docs.developer.amazonservices.com/en_US/products/Products_ListMatchingProducts.html" target="_blank" rel="noopener">ListMatchingProducts</a> API which we will use as an example. To make MWS API testing / learning easy, Amazon provides online testing tool called <a href="https://mws.amazonservices.com/scratchpad/index.html" target="_blank" rel="noopener">MWS ScratchPad</a>. We will use this tool to craft API requests and use that information in ODBC driver SQL queries and later import data in Power BI.</p>
<ol>
<li>Open <a href="https://mws.amazonservices.com/scratchpad/index.html" target="_blank" rel="noopener">MWS ScratchPad</a>  by vising <strong>https://mws.amazonservices.com/scratchpad/index.html</strong></li>
<li>Select <strong>Products</strong> API category and pick <strong>ListMatchingProducts</strong> API</li>
<li>Enter your <strong>SellerID</strong> (i.e. Merchant ID), Developer AccessKey (i.e. <strong>AWSAccessKeyId</strong>) and <strong>Secret Key</strong> we obtained in the previous section. Enter MarketId (e.g. <strong>ATVPDKIKX0DER</strong> for USA Market) and other parameters as below and Click Submit to see response.
<div id="attachment_4844" style="width: 800px" class="wp-caption alignnone"><a href="https://zappysys.com/blog/wp-content/uploads/2018/09/amazon-mws-api-scratchpad-online-testing-tool.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-4844" class="size-full wp-image-4844" src="https://zappysys.com/blog/wp-content/uploads/2018/09/amazon-mws-api-scratchpad-online-testing-tool.png" alt="Using Amazon MWS ScratchPad (API Testing Tool - Created by Amazon)" width="790" height="500" srcset="https://zappysys.com/blog/wp-content/uploads/2018/09/amazon-mws-api-scratchpad-online-testing-tool.png 790w, https://zappysys.com/blog/wp-content/uploads/2018/09/amazon-mws-api-scratchpad-online-testing-tool-300x190.png 300w, https://zappysys.com/blog/wp-content/uploads/2018/09/amazon-mws-api-scratchpad-online-testing-tool-768x486.png 768w" sizes="(max-width: 790px) 100vw, 790px" /></a><p id="caption-attachment-4844" class="wp-caption-text">Using Amazon MWS ScratchPad (API Testing Tool &#8211; Created by Amazon)</p></div></li>
<li>Click on the <strong>Response Details</strong> Tab to extract some important information we will use for ODBC configuration. Notice attributes in red rectangles. They are the ones which we will need in the POST request Body. ZappySys Drivers supply many common parameters automatically but any API endpoint specific parameter must be supplied in the Request Body. For example you dont have to supply <b>SignatureVersion, Timestamp, Signature or SignatureMethod</b>
<div id="attachment_4847" style="width: 933px" class="wp-caption alignnone"><a href="https://zappysys.com/blog/wp-content/uploads/2018/09/amazon-mws-api-response-scratchpad-listmatchingproducts-example.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-4847" class="size-full wp-image-4847" src="https://zappysys.com/blog/wp-content/uploads/2018/09/amazon-mws-api-response-scratchpad-listmatchingproducts-example.png" alt="Calling Amazon MWS API in Scratchpad Testing Tool (Response Details Tab) - ListMatchingProducts Example" width="923" height="527" srcset="https://zappysys.com/blog/wp-content/uploads/2018/09/amazon-mws-api-response-scratchpad-listmatchingproducts-example.png 923w, https://zappysys.com/blog/wp-content/uploads/2018/09/amazon-mws-api-response-scratchpad-listmatchingproducts-example-300x171.png 300w, https://zappysys.com/blog/wp-content/uploads/2018/09/amazon-mws-api-response-scratchpad-listmatchingproducts-example-768x439.png 768w" sizes="(max-width: 923px) 100vw, 923px" /></a><p id="caption-attachment-4847" class="wp-caption-text">Calling Amazon MWS API in Scratchpad Testing Tool (Response Details Tab) &#8211; ListMatchingProducts Example</p></div></li>
</ol>
<p>This API requires Market ID parameter so enter it as per your Market where you selling. For example USA marketplaceid = ATVPDKIKX0DER. You can lookup correct MarketplaceId by <a href="https://docs.developer.amazonservices.com/en_US/dev_guide/DG_Endpoints.html" target="_blank" rel="noopener">checking this help (endpoints / marketplaces)</a>.</p>
<h3></h3>
<h2>Setup Amazon MWS API Connections</h2>
<div class="content_block" id="custom_post_widget-5411"><h3><span style="font-size: 14pt;">Configure ZappySys Data Gateway</span></h3>
Now let's look at steps to configure Data Gateway after installation.
<ol style="margin-left: 0;">
 	<li style="text-align: left;">Assuming you have installed <a href="https://zappysys.com/products/odbc-powerpack/" target="_blank" rel="noopener">ZappySys ODBC PowerPack</a> using default options (Which also enables Data Gateway Service)</li>
 	<li style="text-align: left;">Search "Gateway" in your start menu and click ZappySys Data Gateway
<div class="wp-caption alignnone"><a href="https://zappysys.com/blog/wp-content/uploads/2018/11/start-menu-open-zappysys-data-gateway.png">
<img decoding="async" src="https://zappysys.com/blog/wp-content/uploads/2018/11/start-menu-open-zappysys-data-gateway.png" alt="Open ZappySys Data Gateway" /></a>
<p class="wp-caption-text">Opening ZappySys Data Gateway</p>

</div></li>
 	<li>First, make sure Gateway Service is running (Verify Start icon is disabled)</li>
 	<li>Also, verify Port on General Tab
<div class="wp-caption alignnone"><a href="https://zappysys.com/blog/wp-content/uploads/2018/03/ZappySys-data-gateway-port-5000.png">
<img decoding="async" src="https://zappysys.com/blog/wp-content/uploads/2018/03/ZappySys-data-gateway-port-5000.png" alt="Port Number setting on ZappySys Data Gateway" /></a>
<p class="wp-caption-text">Checking port number setting on ZappySys Data Gateway</p>

</div></li>
 	<li>Now go to Users tab. <strong>Click Add</strong> icon to add a new user. Check Is admin to give access to all data sources you add in future. If you don't check admin then you have to manually configure user permission for each data source.
<div class="wp-caption alignnone"><a href="https://zappysys.com/blog/wp-content/uploads/2018/11/zappysys-data-gateway-add-user.png">
<img loading="lazy" decoding="async" class="alignnone size-full wp-image-5453" src="https://zappysys.com/blog/wp-content/uploads/2018/11/gateway-configure-add-user.png" alt="" width="564" height="438" srcset="https://zappysys.com/blog/wp-content/uploads/2018/11/gateway-configure-add-user.png 564w, https://zappysys.com/blog/wp-content/uploads/2018/11/gateway-configure-add-user-300x233.png 300w" sizes="(max-width: 564px) 100vw, 564px" /></a>
<p class="wp-caption-text">Adding the Gateway user</p>

</div></li>
</ol>
&nbsp;</div>
<h3>Create XML Driver Connection for Amazon MWS API (e.g. RequestReport )</h3>
<p>Some APIs we need to call in this article is XML format and some API (e.g. GetReport) is CSV format &#8211; Tab delimited so we need to create 2 different connections using CSV driver and XML driver. So lets get started with Amazon MWS Connection for XML API.</p>
<ol>
<li>Click on Add New Data source. Name as <strong>AMAZON-MWS-XML</strong> and select <a href="https://zappysys.com/products/odbc-powerpack/odbc-xml-soap-api-driver/" target="_blank" rel="noopener"><strong>Native &#8211; ZappySys XML Driver</strong></a> option.
<div id="attachment_5557" style="width: 572px" class="wp-caption alignnone"><a href="https://zappysys.com/blog/wp-content/uploads/2018/11/odbc_json_driver_add_native_driver.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-5557" class="size-full wp-image-5557" src="https://zappysys.com/blog/wp-content/uploads/2018/11/odbc_json_driver_add_native_driver.png" alt="Add Gateway Data Source" width="562" height="539" srcset="https://zappysys.com/blog/wp-content/uploads/2018/11/odbc_json_driver_add_native_driver.png 562w, https://zappysys.com/blog/wp-content/uploads/2018/11/odbc_json_driver_add_native_driver-300x288.png 300w" sizes="(max-width: 562px) 100vw, 562px" /></a><p id="caption-attachment-5557" class="wp-caption-text">Add Gateway Data Source</p></div></li>
<li>Now click Edit to Configure Settings. For now we will only care OAuth Connection settings. All other options are overwritten in SQL Query.
<div id="attachment_5440" style="width: 572px" class="wp-caption alignnone"><a href="https://zappysys.com/blog/wp-content/uploads/2018/11/gateway-create-datasource-2-2.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-5440" class="size-full wp-image-5440" src="https://zappysys.com/blog/wp-content/uploads/2018/11/gateway-create-datasource-2-2.png" alt="Edit Gateway Data Source Settings" width="562" height="385" srcset="https://zappysys.com/blog/wp-content/uploads/2018/11/gateway-create-datasource-2-2.png 562w, https://zappysys.com/blog/wp-content/uploads/2018/11/gateway-create-datasource-2-2-300x206.png 300w" sizes="(max-width: 562px) 100vw, 562px" /></a><p id="caption-attachment-5440" class="wp-caption-text">Edit Gateway Data Source Settings</p></div></li>
<li>When UI opens for Driver Enter MWS API Service URL as below. Notice that we added /Products/2011-10-01 (This was extracted from previous section). You can check <a href="https://docs.developer.amazonservices.com/en_ES/dev_guide/DG_Endpoints.html" target="_blank" rel="noopener">full list of Amazon MWS Endpoints here</a>. Because we are connecting to USA region we will use below URL.<br />
<pre class="crayon-plain-tag">https://mws.amazonservices.com/Products/2011-10-01</pre>
</li>
<li>Select <strong>OAuth</strong> from the Connection dropdown and Click <strong>Configure Settings</strong></li>
<li>On the Connection UI, Select OAuth Provider <strong>Amazon Market Web Service (MWS)</strong></li>
<li>Enter your API <strong>Access Key</strong> and <strong>Secret Key</strong> (obtained <a href="https://sellercentral.amazon.com/gp/account-manager/home.html/ref=xx_userperms_dnav_userperms" target="_blank" rel="noopener">from here</a>)</li>
<li>Your connection will look like below.
<div id="attachment_4850" style="width: 667px" class="wp-caption alignnone"><a href="https://zappysys.com/blog/wp-content/uploads/2018/09/amazon-mws-api-odbc-driver-connection.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-4850" class="size-full wp-image-4850" src="https://zappysys.com/blog/wp-content/uploads/2018/09/amazon-mws-api-odbc-driver-connection.png" alt="ODBC Connection Credentials for Amazon MWS API (Access Key, Secret Key, URL Endpoint)" width="657" height="570" srcset="https://zappysys.com/blog/wp-content/uploads/2018/09/amazon-mws-api-odbc-driver-connection.png 657w, https://zappysys.com/blog/wp-content/uploads/2018/09/amazon-mws-api-odbc-driver-connection-300x260.png 300w" sizes="(max-width: 657px) 100vw, 657px" /></a><p id="caption-attachment-4850" class="wp-caption-text">ODBC Connection Credentials for Amazon MWS API (Access Key, Secret Key, URL Endpoint)</p></div></li>
<li>Also configure Retry options to handle API limit reached error when you call API too often. For Amazon MWS we get Status code 503 when request is throttled so lets narrow down on which error we want to retry.
<div id="attachment_7156" style="width: 599px" class="wp-caption alignnone"><a href="https://zappysys.com/blog/wp-content/uploads/2018/09/http-retry-settings-oauth-connection.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-7156" class="size-full wp-image-7156" src="https://zappysys.com/blog/wp-content/uploads/2018/09/http-retry-settings-oauth-connection.png" alt="Retry Options" width="589" height="429" srcset="https://zappysys.com/blog/wp-content/uploads/2018/09/http-retry-settings-oauth-connection.png 589w, https://zappysys.com/blog/wp-content/uploads/2018/09/http-retry-settings-oauth-connection-300x219.png 300w" sizes="(max-width: 589px) 100vw, 589px" /></a><p id="caption-attachment-7156" class="wp-caption-text">Retry Options</p></div></li>
<li>Click OK to save OAuth Connection UI to go back to main UI</li>
<li>Now Go to Throttling Tab and enter some delay (e.g. <strong>enter 20000 for 20sec delay after each request</strong>). This will slow down API calls so we don&#8217;t face errors about API Limit reached.</li>
<li>Click OK to Save UI</li>
<li>Click Save button on Gateway UI to save and restart</li>
</ol>
<h3>Create CSV Driver Connection for Amazon MWS API (e.g. GetReport )</h3>
<p>Now lets create a connection CSV API (e.g. <a href="https://docs.developer.amazonservices.com/en_UK/reports/Reports_GetReport.html" target="_blank" rel="noopener">GetReport</a> ).</p>
<p>Follow almost same steps as previous section except use CSV Driver when you click on Add new Data source select <strong><a href="https://zappysys.com/products/odbc-powerpack/odbc-csv-rest-api-driver/" target="_blank" rel="noopener">Native &#8211; ZappySys CSV Driver</a></strong> and name data source as <strong>AMAZON-MWS-CSV</strong> . As we mentioned for now we mostly want to setup Connection and not worry about Request Body, Pagination etc.</p>
<h3>Create Linked Server for SQL Server</h3>
<p>Run following Script in SSMS to create Linked servers. Change ######## with Your gateway password. Change localhost with machine name or IP where ZappySys Gateway Is running. Use localhost if SQL Server and Gateway both on the same machine.</p><pre class="crayon-plain-tag">USE [master]
GO

EXEC master.dbo.sp_addlinkedserver @server = N'AMAZON-MWS-XML', @srvproduct=N'', @provider=N'SQLNCLI', @datasrc=N'localhost,5000', @catalog=N'AMAZON-MWS-XML'
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'AMAZON-MWS-XML',@useself=N'False',@locallogin=NULL,@rmtuser=N'tdsuser',@rmtpassword='########'
GO

EXEC master.dbo.sp_addlinkedserver @server = N'AMAZON-MWS-CSV', @srvproduct=N'', @provider=N'SQLNCLI', @datasrc=N'localhost,5000', @catalog=N'AMAZON-MWS-CSV'
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'AMAZON-MWS-CSV',@useself=N'False',@locallogin=NULL,@rmtuser=N'tdsuser',@rmtpassword='########'
GO</pre><p>
If you want to know how to configure Linked Server using UI then <a href="https://zappysys.com/blog/import-rest-api-json-sql-server/" target="_blank" rel="noopener">check this article</a>.</p>
<p>&nbsp;</p>
<h2>Amazon MWS ListOrders Example</h2>
<p>Now lets look at how to call ListOrders request with pagination in SQL Server. Create a following Stored Procedure to List MWS Orders. If you want to extract many orders then call Report rather than this proc (See next section for generating reports)</p><pre class="crayon-plain-tag">USE MyDatabase
GO
/*
Example: 
 exec usp_MWS_ListOrders @SellerId='Axxxxxxx', @MarketplaceId ='Bxxxxxxx',@CreatedAfter='2019-01-01'  
*/
Create proc [dbo].[usp_MWS_ListOrders]
	@SellerId varchar(100),
	@MarketplaceId varchar(100),
	@CreatedAfter varchar(100),
	@CreatedBefore varchar(100)=null,
	@MaxRows int=0
as
declare @sql varchar(max) 
declare @limitClase varchar(100)=''
if(@MaxRows&gt;0)
	set @limitClase	=' LIMIT ' + cast(@MaxRows as varchar(20))

--//Confirm ISO Date format 2019-06-01T04%3A00%3A00Z  rather 2019-06-01T04:00:00Z
if(isnull(@CreatedAfter,'')&lt;&gt;'')
begin
	set @CreatedAfter='&amp;CreatedAfter=' + @CreatedAfter
	set @CreatedAfter=replace(@CreatedAfter,':','%3A')
	if(@CreatedAfter NOT LIKE @CreatedAfter + 'T%')
		set @CreatedAfter=@CreatedAfter + 'T00%3A00%3A00Z'
	if(@CreatedAfter NOT LIKE @CreatedAfter + '%Z')
		set @CreatedAfter=@CreatedAfter + 'Z'
	--//T04%3A00%3A00Z
end
if(isnull(@CreatedBefore,'')&lt;&gt;'')
begin
	set @CreatedBefore='&amp;CreatedBefore=' + @CreatedBefore
	set @CreatedBefore=replace(@CreatedBefore,':','%3A')
	if(@CreatedBefore NOT LIKE @CreatedBefore + 'T%')
		set @CreatedBefore=@CreatedBefore + 'T00%3A00%3A00Z'
	if(@CreatedBefore NOT LIKE @CreatedBefore + '%Z')
		set @CreatedBefore=@CreatedBefore + 'Z'
end

set @CreatedAfter = isnull(@CreatedAfter,'')
set @CreatedBefore = isnull(@CreatedBefore,'')


set @sql = 'SELECT * FROM OPENQUERY([AMAZON-MWS-XML]
, ''
SELECT ReportRequestId FROM $
' + @limitClase +' 
WITH(
     Src=''''https://mws.amazonservices.com/Orders/2013-09-01''''
	,Filter=''''$.RequestReportResponse.RequestReportResult.ReportRequestInfo''''
	,ElementsToTreatAsArray=''''Order''''
	,RequestData=''''Action=ListOrders[$tag$]' + @CreatedAfter + @CreatedBefore + '&amp;MarketplaceId.Id.1='+ @MarketplaceId +'&amp;SellerId='+ @SellerId +'''''
	,RequestMethod=''''POST''''
	,NextUrlAttributeOrExpr=''''$.ListOrders[$tag$]Response.ListOrders[$tag$]Result.NextToken''''
	,NextUrlSuffix=''''&amp;NextToken=&lt;%nextlink_encoded%&gt;''''
	,WaitTimeMs=20000 -- slow down to avoid throttling. 6 requests per min
	,HasDifferentNextPageInfo=''''True''''
	,EnablePageTokenForBody=''''True''''
	,PagePlaceholders=''''body=|ByNextToken;filter=|ByNextToken''''
	--,DataConnectionType=''''OAuth''''
	--,ScopeSeparator=''''{space}''''
	--,ServiceProvider=''''AmazonMWS''''
	--,ClientId=''''AKIxxxxxx''''
	--,ClientSecret=''''AKIxxxxxx''''
	--,UseCustomApp=''''True''''
	,CacheFileLocation=''''c:\temp\mws-orders.cache''''
	,CacheEntryTtl=300 --send every 5 mins else use from cache
	,IncludeParentColumns=''''False''''
)
'')'
print @sql

EXECUTE( @sql)</pre><p>
Here is how to call this proc. Change SellerId, MarketplaceId and Date.</p><pre class="crayon-plain-tag">exec usp_MWS_ListOrders @SellerId='Axxxxxxx', @MarketplaceId ='Bxxxxxxx',@CreatedAfter='2019-01-01'</pre><p>
&nbsp;</p>
<h2>Download Amazon MWS Report data in SQL Server (CSV / XML Format)</h2>
<p>Now lets look at how to extract data from <a href="https://docs.developer.amazonservices.com/en_UK/reports/Reports_ReportType.html" target="_blank" rel="noopener">Custom Report API</a> (You must need ODBC PowerPack <strong>v1.1.1</strong> or higher). However reading data from Reports not single step process because report generation is Job style API. Which means you send report request and wait  until its done. Once Report ready you have to read in CSV format or XML. Some Reports only available in CSV format. <a href="https://docs.developer.amazonservices.com/en_UK/reports/Reports_Overview.html" target="_blank" rel="noopener">Check this post</a> to understand how complex it can be to get data. We will make it simple for you to understand this in 3 steps. Basically calling reports requires minimum 3 API calls (see below)</p>
<ol>
<li>Create a new report request &#8211; Cal <a href="https://docs.developer.amazonservices.com/en_UK/reports/Reports_RequestReport.html" target="_blank" rel="noopener">RequestReport</a> API . It returns <strong>ReportRequestId</strong> (You can use it in the next step)</li>
<li>Check Report Status see its done &#8211; Call <a href="https://docs.developer.amazonservices.com/en_UK/reports/Reports_GetReportRequestList.html" target="_blank" rel="noopener">GetReportRequestList</a> API (Pass <strong>ReportRequestId</strong> got in the previous step to get data for only one Report request we care). Keep checking Report Status every few seconds until you get <strong>_DONE_</strong>  or <strong>_DONE_NO_DATA_</strong> status in response.</li>
<li>Read Report Data &#8211; Call <a href="https://docs.developer.amazonservices.com/en_UK/reports/Reports_GetReport.html" target="_blank" rel="noopener">GetReport</a>. This API call returns CSV or XML data. So use correct Driver for this step. If CSV data is returned then we must use CSV Driver rather than XML Driver.</li>
</ol>
<h3>Method 1 &#8211; Single query approach (New Driver)</h3>
<p>In new driver ZappySys added few new features which makes it possible to call above 3 steps process in a single query. New query syntax offers StatusCheck and Mixing Content Formats using same driver. Because Most MWS Reports are in CSV Format we have to use CSV Driver but oddly first 2 steps listed in above sections are in XML Format so we have to use XML driver. Technically we need atleast 2 steps (i.e 2 queries) but we will show you how to achieve using single query as below.</p>
<ol>
<li>Assuming you have followed steps to create a linked server AMAZON-MWS-CSV (see previous section)</li>
<li>Run below query. Replace necessary parameters as per your need. (i.e MarketplaceId , SellerId, CreatedAfter date)<br />
<pre class="crayon-plain-tag">--- //////////////////////////////////////////////////////////////////////////
-- Change _GET_MERCHANT_LISTINGS_DATA_ to something else if you need different report type (all 3 steps) -- https://docs.developer.amazonservices.com/en_US/reports/Reports_ReportType.html
-- Replace MarketplaceId in all 3 steps (i.e for USA use ATVPDKIKX0DER) --https://docs.developer.amazonservices.com/en_US/dev_guide/DG_Endpoints.html
-- Replace SellerId in all 3 steps
-- Remove or Change CreatedAfter in first step (or use CreatedBefore parameter instread of CreatedAfter)
--- //////////////////////////////////////////////////////////////////////////
select * into tmpMWS_Report from OPENQUERY([AMAZON-MWS-CSV],
'
SELECT s3.* FROM $
WITH(
Src=''https://mws.amazonservices.com/Reports/2009-01-01'',RequestMethod=''POST''
,RequestData=''Action=RequestReport&amp;ReportType=_GET_MERCHANT_LISTINGS_DATA_&amp;MarketplaceId=ATVPDKIKX0DER&amp;SellerId=Axxxxxxxxxx&amp;CreatedAfter=2017-12-31T04%3A00%3A00Z''
,IncludeParentColumns=''False''
,EnableRawOutputModeSingleRow=''True''
,RawOutputFilterExpr=''//*[local-name()="ReportRequestId"]'' 
,RawOutputDataRowTemplate=''{ReportRequestId:"[$1]"}'' 
,RawOutputExtractMode=''Xml'' 
,WaitTimeMs=5000
,Meta=''[{"Name": "ReportRequestId","Type": "Int64"}]''
,Alias=''s1''

,Join1_alias=''s2''	
,Join1_Src=''https://mws.amazonservices.com/Reports/2009-01-01'',Join1_RequestMethod=''POST''
,Join1_RequestData=''Action=GetReportRequestList&amp;ReportRequestIdList.Id.1=[$s1.ReportRequestId$]&amp;MarketplaceId=ATVPDKIKX0DER&amp;SellerId=Axxxxxxxxxxxxx''
,Join1_EnableRawOutputModeSingleRow=''True''
,Join1_RawOutputFilterExpr=''//*[local-name()="ReportProcessingStatus"]||//*[local-name()="GeneratedReportId"]'' 
,Join1_RawOutputDataRowTemplate=''{ReportProcessingStatus:"[$1]",GeneratedReportId:"[$2]"}'' 
,Join1_RawOutputExtractMode=''Xml'' 
,Join1_EnableStatusCheck=''True'', 
,Join1_StatucCheckMaxWaitSeconds=300,
,Join1_StatucCheckIterationWaitSeconds=25,
,Join1_StatusSuccessValue=''_DONE_''
,Join1_StatusFailedValue=''_DONE_NO_DATA_|_CANCELLED_''

,Join2_Alias=''s3''
,Join2_Src=''https://mws.amazonservices.com/Reports/2009-01-01'',Join2_RequestMethod=''POST''
,Join2_RequestData=''Action=GetReport&amp;ReportId=[$s2.GeneratedReportId$]&amp;MarketplaceId=ATVPDKIKX0DER&amp;SellerId=Axxxxxxxxxxxxxx''	
,Join2_ColumnDelimiter=''{TAB}''
,Join2_ResponseCharset=''Windows-1252''	 
,Join2_EnableStatusCheck=''False'' 
,Join2_EnableRawOutputModeSingleRow=''False''
,Join2_WaitTimeMs=10000
)') 
go
select * from tmpMWS_Report</pre>
&nbsp;</li>
</ol>
<p>&nbsp;</p>
<p><strong>Performance Tip</strong></p>
<p>If you like to improve performance and dont want to use SELECT INTO approach to load into temp table as above then you can use EXEC (&#8230;.) AT YourLinkedServerName  as below.</p>
<p>Advantage of this method is your Query speed will increase because system calls API only once when you call EXEC AT. In OPENROWSET it needs to call above query twice (Once to obtain metadata and once to get data).</p><pre class="crayon-plain-tag">INSERT INTO tmpMWS_Report
EXEC('select s3.* .................. ') AT [AMAZON-MWS-CSV]</pre><p>
<div class="su-note"  style="border-color:#e5de9d;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;"><div class="su-note-inner su-u-clearfix su-u-trim" style="background-color:#fff8b7;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;">When you use OPENQUERY / EXEC..AT with Data Gateway there is a known limitation with SQL Query Length. Your query must be less than 2048 characters otherwise you may get [**** Data is invalid error ****] Try to avoid column names for long query and use SELECT * INTO temp_table FROM OPENQUERY(&#8230;..) approach. </div></div>
<p>&nbsp;</p>
<h3>Method 2 &#8211; Multiple query approach (For old driver)</h3>
<p>Now lets see how to load Amazon MWS data in SQL Server using <strong>old driver</strong> (<strong>v1.1.2 or older</strong>) which didnt support single query approach like previous section. If you are using older driver or for some reason you like to split steps into multiple procedures then use below approach.</p>
<h4>usp_MWS_Report  Stored Proc ( Generate ReportRequest, Wait until done, Read data )</h4>
<pre class="crayon-plain-tag">USE MyDatabase
GO

/*
Examples: 
Get ReportType from here https://docs.developer.amazonservices.com/en_UK/reports/Reports_ReportType.html

exec usp_MWS_Report @MarketplaceId ='ATVPDKIKX0DER', @SellerId='AZxxxxxxxx', @ReportType = '_GET_MERCHANT_LISTINGS_DATA_'
exec usp_MWS_Report @MarketplaceId ='ATVPDKIKX0DER', @SellerId='AZxxxxxxxx', @ReportType = '_GET_FLAT_FILE_ORDER_REPORT_DATA_'

--Do not Throw Error if no data found (return empty resultset or run custom sql)
exec usp_MWS_Report @MarketplaceId ='ATVPDKIKX0DER', @SellerId='AZxxxxxxxx', @ReportType = '_GET_FLAT_FILE_ORDER_REPORT_DATA_',@ThrowErrIfNoData=0,@EmptyRowSql='select top 0 * from Orders'
--Supply date range
exec usp_MWS_Report @MarketplaceId ='ATVPDKIKX0DER', @SellerId='AZxxxxxxxx', @ReportType = '_GET_MERCHANT_LISTINGS_DATA_', @StartDate='2019-01-01T00:00:00Z', @EndDate='2019-01-31T00:00:00Z'

--loading into table 

--//////////////////////////////////
— Step-1 : Create Local Linked server to point to self
--//////////////////////////////////
USE [master]
GO
--change default catalog
--For MSSQL 2012, 2014, 2016, 2017, and 2019 use @provider=N'MSOLEDBSQL' below (SQL Server Native Client 11.0)---
EXEC master.dbo.sp_addlinkedserver @server = N'ME', @srvproduct=N'', @provider=N'SQLNCLI11', @datasrc=N'localhost', @catalog=N'Northwind'
--For MSSQL 2022 or higher use @provider=N'MSOLEDBSQL' below (Microsoft OLE DB Driver for SQL Server)---
--EXEC master.dbo.sp_addlinkedserver @server = N'ME', @srvproduct=N'', @provider=N'MSOLEDBSQL', @datasrc=N'localhost', @catalog=N'Northwind'

EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'ME',@useself=N'True',@locallogin=NULL,@rmtuser=NULL,@rmtpassword=NULL
GO
--//////////////////////////////////
— Step-2 : Enable RPC OUT and Disable MSDTC
--//////////////////////////////////
EXEC sp_serveroption 'ME', 'rpc out', true;  
GO
--Below needed to support EXEC + INSERT (dynamic query)
EXEC sp_serveroption 'ME', 'remote proc transaction promotion', false;
GO
--test simple query
select * from OPENQUERY(ME,'select 1')
GO

--//////////////////////////////////
— Step-3 : Load data into table from MWS Report
--//////////////////////////////////
SELECT * INTO #amazon_mws_report
FROM OPENQUERY(me,'
SET NOCOUNT ON;
EXEC usp_MWS_Report 
   @Columns=''[item-name], [item-description], [listing-id]'',
   @MarketplaceId =''ATVPDKIKX0DER'', 
   @SellerId=''Axxxxxxxxxxxxxxxxx'', 
   @ReportType = ''_GET_MERCHANT_LISTINGS_DATA_''
WITH RESULT SETS 
(
	(itmname varchar(1000),itmdesc varchar(1000),itmid varchar(1000))
)
')

select * from #amazon_mws_report


*/
CREATE proc [dbo].[usp_MWS_Report]
	@MarketplaceId varchar(100),
	@SellerId varchar(100),
	@ReportType varchar(100)='_GET_MERCHANT_LISTINGS_DATA_',
	@StartDate varchar(100)=null,
	@EndDate varchar(100)=null,
	@ReportId bigint=null,  ---i.e. 14783134522018025
	@ThrowErrIfNoData bit=1,
	@EmptyRowSql varchar(1000)=null, --SQL to run if no data found
	@Columns varchar(8000)='*'  --report columns which goes in final SELECT  e.g. [item-name], [item-description], [listing-id] ....
as


declare @retGeneratedReportId bigint
set @retGeneratedReportId=@ReportId
---////// STEP 1 /////////
if(@ReportId is null)
begin
	create table #step1(ReportRequestId bigint)
	insert into #step1
	exec usp_MWS_RequestReport @ReportType,@MarketplaceId,@SellerId,@StartDate,@EndDate

	--select * from #step1 --debug

	declare @retReportRequestId bigint
	select @retReportRequestId=ReportRequestId from #step1

	---////// STEP 2 /////////
	declare @status varchar(100)
	declare @cnt int
	create table #step2(ReportProcessingStatus varchar(100),GeneratedReportId bigint)
	
	--Keep looping until status is done or we waited too long
	while(isnull(@status,'') IN ('','_SUBMITTED_','_IN_PROGRESS_') )
	begin
		truncate table #step2
		insert into #step2
		exec usp_MWS_GetReportIdAndStatus @retReportRequestId,@MarketplaceId,@SellerId 
	
		select @status=ReportProcessingStatus, @retGeneratedReportId=GeneratedReportId from #step2
		if(isnull(@status,'') IN ('','_SUBMITTED_','_IN_PROGRESS_') )			
		begin
			--amazon says dont check often https://docs.developer.amazonservices.com/en_UK/reports/Reports_GetReportRequestList.html
			Print 'Status='+  isnull(@status,'') +'. Checking after 45 sec... #' + cast(@cnt as varchar(10))
			WAITFOR DELAY '00:00:45'			
		end
		else
			print @status

		set @cnt=@cnt+1

		--if(@cnt&gt;50)
			--//throw err?
	end
	--select * from #step2 --debug
end

if(@retGeneratedReportId is null and @status='_DONE_NO_DATA_')
begin
	if(@ThrowErrIfNoData=1)
		RAISERROR('Cannot generate report - No data found for specified criteria',16,1); 
	else if (isnull(@EmptyRowSql,'')&lt;&gt;'')
		execute(@EmptyRowSql)
end
else if(@retGeneratedReportId is null)
	RAISERROR('Cannot generate report - Unknown error (either report got cancelled or other error occurred)',16,1); 

	
---////// STEP 3 /////////
--If xml format of report data then use XML driver else CSV (most are Tab delimited reports in CSV format)
--exec usp_MWS_GetReportDataXml @retGeneratedReportId,@MarketplaceId,@SellerId
exec usp_MWS_GetReportDataCsv @retGeneratedReportId,@MarketplaceId,@SellerId,@Columns

drop table #step1
drop table #step2

GO</pre>
&nbsp;</p>
<h4>usp_MWS_RequestReport  Stored Proc ( Step1 &#8211; Create Report Request )</h4>
<p>&nbsp;</p><pre class="crayon-plain-tag">USE [MyDatabase]
GO

CREATE proc [dbo].[usp_MWS_RequestReport]
	@ReportType varchar(100),
	@MarketplaceId varchar(100),
	@SellerId varchar(100),
	@StartDate varchar(100)=null,
	@EndDate varchar(100)=null
as

/*Learn more : https://docs.developer.amazonservices.com/en_UK/reports/Reports_RequestReport.html */

--//Confirm ISO Date format 2019-06-01T04%3A00%3A00Z  rather 2019-06-01T04:00:00Z
if(isnull(@StartDate,'')&lt;&gt;'')
begin
	set @StartDate='&amp;StartDate=' + @StartDate
	set @StartDate=replace(@StartDate,':','%3A')
	if(@StartDate NOT LIKE @StartDate + 'T%')
		set @StartDate=@StartDate + 'T00%3A00%3A00Z'
	if(@StartDate NOT LIKE @StartDate + '%Z')
		set @StartDate=@StartDate + 'Z'
	--//T04%3A00%3A00Z
end
if(isnull(@EndDate,'')&lt;&gt;'')
begin
	set @EndDate='&amp;EndDate=' + @EndDate
	set @EndDate=replace(@EndDate,':','%3A')
	if(@EndDate NOT LIKE @EndDate + 'T%')
		set @EndDate=@EndDate + 'T00%3A00%3A00Z'
	if(@EndDate NOT LIKE @EndDate + '%Z')
		set @EndDate=@EndDate + 'Z'
end

set @StartDate = isnull(@StartDate,'')
set @EndDate = isnull(@EndDate,'')

declare @sql varchar(max) 
set @sql = 'SELECT * FROM OPENQUERY([AMAZON-MWS-XML]
, ''
SELECT ReportRequestId FROM $
WITH(
	Src=''''https://mws.amazonservices.com/Reports/2009-01-01'''',RequestMethod=''''POST''''
	--,ElementsToTreatAsArray=''''Product''''
	,Filter=''''$.RequestReportResponse.RequestReportResult.ReportRequestInfo''''
	,RequestData=''''Action=RequestReport&amp;ReportType=' + @ReportType  + '&amp;MarketplaceId='+ @MarketplaceId +'&amp;SellerId='+ @SellerId + @StartDate + @EndDate +'''''
	,CacheFileLocation=''''c:\temp\mws-cache-step-1.cache''''
	,CacheEntryTtl=300 --send every 5 mins else use from cache
	,WaitTimeMs=''''300''''
	,IncludeParentColumns=''''False''''
	,Meta=''''[{"Name": "ReportRequestId","Type": "Int64"}]''''
)'')'
--print @sql

EXECUTE( @sql)
--sleep 25 seconds after this - hope report is ready by that time else We have to loop
WAITFOR DELAY '00:00:25'  --lets wait 30 sec... incase we get luck and report is done?
GO</pre><p>
&nbsp;</p>
<p>&nbsp;</p>
<h4>usp_MWS_GetReportIdAndStatus Stored Proc ( Step2 &#8211; Get Report Id and Report Status )</h4>
<p>&nbsp;</p><pre class="crayon-plain-tag">USE MyDatabase
GO


CREATE proc [dbo].[usp_MWS_GetReportIdAndStatus]
	@ReportRequestId bigint,
	@MarketplaceId varchar(100),
	@SellerId varchar(100)
as

declare @sql varchar(max) 
set @sql = 'SELECT * FROM OPENQUERY([AMAZON-MWS-XML]
, ''SELECT *  FROM $
WITH(
	 Src=''''https://mws.amazonservices.com/Reports/2009-01-01'''',RequestMethod=''''POST''''
	,ElementsToTreatAsArray=''''ReportRequestInfo''''
	,Filter=''''$.GetReportRequestListResponse.GetReportRequestListResult.ReportRequestInfo''''
	,RequestData=''''Action=GetReportRequestList&amp;ReportRequestIdList.Id.1=' + cast(@ReportRequestId as varchar(20)) + '&amp;MarketplaceId='+ @MarketplaceId +'&amp;SellerId='+ @SellerId +'''''
	,WaitTimeMs=''''300''''
	,IncludeParentColumns=''''False''''
	--,CacheFileLocation=''''c:\temp\mws-cache-step-2.cache''''
	--,CacheEntryTtl=10  --do not use from cache too old.. but cache still prevents too many requests
	,Meta=''''[{"Name": "ReportProcessingStatus","Type": "String", Length: 100},{"Name": "GeneratedReportId","Type": "Int64"}]''''	
)'')'

--print @sql

EXECUTE( @sql)

GO</pre><p>
&nbsp;</p>
<h4>usp_MWS_GetReportDataCsv Stored Proc (Step3 &#8211; Get Report Data in CSV format )</h4>
<p>Last step in report generation is download the report data in CSV format.</p><pre class="crayon-plain-tag">USE MyDatabase
GO

CREATE proc [dbo].[usp_MWS_GetReportDataCsv]
	@ReportId bigint,
	@MarketplaceId varchar(100),
	@SellerId varchar(100),
	@Columns varchar(8000)='*'

as

declare @sql varchar(max) 
set @sql = 'SELECT '+ @Columns +' FROM OPENQUERY([AMAZON-MWS-CSV], 
''SELECT * FROM $
WITH(
    Src=''''https://mws.amazonservices.com/Reports/2009-01-01'''',RequestMethod=''''POST''''
	,RequestData=''''Action=GetReport&amp;ReportId=' + cast(@ReportId as varchar(20)) + '&amp;MarketplaceId='+ @MarketplaceId +'&amp;SellerId='+ @SellerId +'''''
	,WaitTimeMs=''''300''''
	,ColumnDelimiter=''''{TAB}''''
	,ResponseCharset=''''Windows-1252''''	
	,CacheFileLocation=''''c:\temp\mws-cache-step-3.cache''''
	,CacheEntryTtl=300 --once report is generated lets try to read from cache 
	)''
)'

print @sql

EXECUTE( @sql)
GO</pre><p>
&nbsp;</p>
<h4>Example &#8211; Import data from Amazon MWS into SQL Server Table</h4>
<p>Finally when we have all stored procs created we can load into target table as below. In our previous article we saw how to use SELECT INTO along with OPENQUERY to load data into new temp table or insert into some existing table. However when you want to load Stored Proc output into table its not straight forward specially when we calling dynamic SQL.</p>
<p>Three tricks worth mentioning here which makes it possible to load data from stored proc into temp table dynamically.</p>
<ol>
<li>Create a linked server to Self so we can use OPENQUERY against to call stored proc so its easy to use <strong>SELECT INTO</strong>.</li>
<li>Use <strong>WITH RESULT SETS</strong> to describe metadata of output. This is needed because we are using dynamic SQL inside proc and WITH RESULT SETS describes the metadata.</li>
<li>Use of SET NO COUNT ON to avoid error like below<br />
<pre class="crayon-plain-tag">"SOMESERVERNAME" indicates that either the object has no columns 
or the current user does not have permissions on that object</pre>
</li>
<li>If you dont do above tricks then you may see errors like <a href="https://stackoverflow.com/questions/3795263/errors-insert-exec-statement-cannot-be-nested-and-cannot-use-the-rollback-s" target="_blank" rel="noopener">this</a> (INSERT is not allowed when we use DYNAMIC SQL inside nested Stored Procs)</li>
</ol>
<p>To load output into table you must know column names from the output.  If you dont know you can try to run stored proc without @Columns like below.</p><pre class="crayon-plain-tag">EXEC usp_MWS_Report @MarketplaceId =''ATVPDKIKX0DER'', @SellerId=''Axxxxxxxxxxxxx'', @ReportType = ''_GET_MERCHANT_LISTINGS_DATA_''</pre><p>
Once we know columns from report, you can run following script to insert into table.</p>
<p><strong>Full Script &#8211; Load MWS Report Output into Table</strong></p><pre class="crayon-plain-tag">--//////////////////////////////////
— Step-1 : Create Local Linked server to point to self
--//////////////////////////////////
USE [master]
GO
--change default catalog
--For MSSQL 2012, 2014, 2016, 2017, and 2019 use @provider=N'MSOLEDBSQL' below (SQL Server Native Client 11.0)---
EXEC master.dbo.sp_addlinkedserver @server = N'ME', @srvproduct=N'', @provider=N'SQLNCLI11', @datasrc=N'localhost', @catalog=N'Northwind'
--For MSSQL 2022 or higher use @provider=N'MSOLEDBSQL' below (Microsoft OLE DB Driver for SQL Server)---
--EXEC master.dbo.sp_addlinkedserver @server = N'ME', @srvproduct=N'', @provider=N'MSOLEDBSQL', @datasrc=N'localhost', @catalog=N'Northwind'

EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'ME',@useself=N'True',@locallogin=NULL,@rmtuser=NULL,@rmtpassword=NULL
GO
--//////////////////////////////////
— Step-2 : Enable RPC OUT and Disable MSDTC
--//////////////////////////////////
EXEC sp_serveroption 'ME', 'rpc out', true;  
GO
--Below needed to support EXEC + INSERT (dynamic query)
EXEC sp_serveroption 'ME', 'remote proc transaction promotion', false;
GO
--test simple query
select * from OPENQUERY(ME,'select 1')
GO

--//////////////////////////////////
— Step-3 : Load data into temp table from Amazon MWS Report
--//////////////////////////////////
SELECT * INTO #amazon_mws_report
FROM OPENQUERY(me,'
SET NOCOUNT ON;
EXEC usp_MWS_Report 
   @Columns=''[item-name], [item-description], [listing-id]'',
   @MarketplaceId =''ATVPDKIKX0DER'', 
   @SellerId=''Axxxxxxxxxxxxx'', 
   @ReportType = ''_GET_MERCHANT_LISTINGS_DATA_''
WITH RESULT SETS 
(
	(itmname varchar(1000),itmdesc varchar(1000),itmid varchar(1000))
)
')

select * from #amazon_mws_report</pre><p>
<div id="attachment_7192" style="width: 865px" class="wp-caption alignnone"><a href="https://zappysys.com/blog/wp-content/uploads/2019/05/import-amazon-mws-data-into-sql-server-table-generate-report.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-7192" class="size-full wp-image-7192" src="https://zappysys.com/blog/wp-content/uploads/2019/05/import-amazon-mws-data-into-sql-server-table-generate-report.png" alt="Import Amazon MWS Data into SQL Table (Load Report output into temp table)" width="855" height="499" srcset="https://zappysys.com/blog/wp-content/uploads/2019/05/import-amazon-mws-data-into-sql-server-table-generate-report.png 855w, https://zappysys.com/blog/wp-content/uploads/2019/05/import-amazon-mws-data-into-sql-server-table-generate-report-300x175.png 300w, https://zappysys.com/blog/wp-content/uploads/2019/05/import-amazon-mws-data-into-sql-server-table-generate-report-768x448.png 768w" sizes="(max-width: 855px) 100vw, 855px" /></a><p id="caption-attachment-7192" class="wp-caption-text">Import Amazon MWS Data into SQL Table (Load Report output into temp table)</p></div>
<h2>Conclusion</h2>
<p>In this article, we saw how to load Amazon MWS Data into SQL Server. We used simple SQL queries with ZappySys XML / CSV Driver to pull data from Amazon MWS API. <a href="https://zappysys.com/products/odbc-powerpack/">ZappySys ODBC PowerPack</a> makes it super easy to consume data from virtually any API (JSON / XML or CSV Web Services), no coding required. <a href="https://zappysys.com/products/odbc-powerpack/download/">Download here</a> to get started with ZappySys ODBC drivers.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a href="https://zappysys.com/blog/import-amazon-mws-data-sql-server-t-sql/">How to import Amazon MWS data into SQL Server (T-SQL)</a> appeared first on <a href="https://zappysys.com/blog">ZappySys Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
