
Here’s a script you can use to automate data loading from SQL Server to Snowflake:
import snowflake.connector
import pyodbc
# set up Snowflake connection
conn = snowflake.connector.connect(
user='YOUR_SNOWFLAKE_USERNAME',
password='YOUR_SNOWFLAKE_PASSWORD',
account='YOUR_SNOWFLAKE_ACCOUNT',
warehouse='YOUR_SNOWFLAKE_WAREHOUSE',
database='YOUR_SNOWFLAKE_DATABASE',
schema='YOUR_SNOWFLAKE_SCHEMA'
)
# set up SQL Server connection
server = 'YOUR_SQL_SERVER_NAME'
database = 'YOUR_SQL_SERVER_DATABASE'
username = 'YOUR_SQL_SERVER_USERNAME'
password = 'YOUR_SQL_SERVER_PASSWORD'
driver = '{ODBC Driver 17 for SQL Server}'
cnxn = pyodbc.connect(f'DRIVER={driver};SERVER={server};DATABASE={database};UID={username};PWD={password}')
# specify the SQL query to extract data from SQL Server
sql_query = """
SELECT * FROM YOUR_SQL_SERVER_TABLE
"""
# execute the query and fetch the results
cursor = cnxn.cursor()
cursor.execute(sql_query)
results = cursor.fetchall()
# create a Snowflake cursor and execute the Snowflake query to load the data
sf_cursor = conn.cursor()
sf_query = f"""
COPY INTO YOUR_SNOWFLAKE_TABLE FROM @%YOUR_SNOWFLAKE_STAGE
FILE_FORMAT = (TYPE = CSV, SKIP_HEADER = 1)
"""
sf_cursor.execute(sf_query, results)
# close connections
cnxn.close()
sf_cursor.close()
conn.close()
This script connects to both the SQL Server and Snowflake databases, extracts data from SQL Server using a SQL query, and then loads the data into a Snowflake table using a COPY INTO command. You’ll need to replace the placeholders with your own values, such as your Snowflake username, password, account, etc.
Note that this script assumes that you have set up a Snowflake stage to load the data into, and that you have created a file format for the data in that stage. You’ll need to modify the COPY INTO command to match your specific stage and file format.

One response to “Automate Data Loading from SQL Server to Snowflake using Python”
Thanks for the great code snippet, it’s just what I needed!
One question, how does the data from SQL Server get into the Snowflake stage area?
It seems the COPY INTO statement is expecting data in a staged file but I don’t see in the code where the data was moved from SQL Server into a file in Snowflake stage?
Thanks again!