Sql-server – Pulling SQL Server data into Excel

excelodbcsql server

I'm trying to pull data from an SQL Server database into Excel 2016 via ODBC / Microsoft Query (built in to Excel).

I'd like to have a dropdown of companies, where after a company is selected from the dropdown, all contacts for that company (from a separate contacts table) are displayed.

From what I've learned so far I need to use :field or @field to indicate that the user chooses – something like:

SELECT Company.CompanyName,
       CompanyContacts.Forename,
       CompanyContacts.Surname,
       CompanyContacts.Email
FROM Commercial.CompanyContacts CompanyContacts
     INNER JOIN Commercial.Company Company
        ON (CompanyContacts.CompanyID = Company.CompanyID)
WHERE (UPPER (Company.CompanyName) = UPPER (@CompanyName))

But Excel / MS Query returns:

"Must declare the scalar variable "@CompanyName". Statement(s) could not be prepared."

Can anyone advise on how I declare the scalar variable? Assuming that's even what I'm actually needing to do here. Many thanks.

Best Answer

Have your declaration at the top.. Variables are declared in the body of a batch or procedure with the DECLARE statement and are assigned values by using either a SET or SELECT statement.

DECLARE @CompanyName VARCHAR(200);
SET @CompanyName = 'CompanyName';

SELECT Company.CompanyName,
       CompanyContacts.Forename,
       CompanyContacts.Surname,
       CompanyContacts.Email
FROM Commercial.CompanyContacts CompanyContacts
     INNER JOIN Commercial.Company Company
        ON (CompanyContacts.CompanyID = Company.CompanyID)
WHERE (UPPER (Company.CompanyName) = UPPER (@CompanyName))