36

I'm using MS Excel to get data from a MySQL database through ODBC.
I successfully get data using an SQL query. But now I want that query to be parameterized.
So I wonder If it is possible to use a cell value (a spreadsheet cell) as a parameter for such a query.
For example, for this query:

select name from user where id=1

I'd like to get the id value from, say, cell D4 in the spreadsheet.

Is that the proper approach to parameterize a query? and how can I do it?

Thanks.

GetFree
  • 40,278
  • 18
  • 77
  • 104

4 Answers4

36

I had the same problem as you, Noboby can understand me, But I solved it in this way.

SELECT NAME, TELEFONE, DATA
FROM   [sheet1$a1:q633]
WHERE  NAME IN (SELECT * FROM  [sheet2$a1:a2])

you need insert a parameter in other sheet, the SQL will consider that information like as database, then you can select the information and compare them into parameter you like.

GetFree
  • 40,278
  • 18
  • 77
  • 104
Joaquim
  • 384
  • 3
  • 2
12

If you are using microsoft query, you can add "?" to your query...

select name from user where id= ?

that will popup a small window asking for the cell/data/etc when you go back to excel.

In the popup window, you can also select "always use this cell as a parameter" eliminating the need to define that cell every time you refresh your data. This is the easiest option.

Community
  • 1
  • 1
pojomx
  • 780
  • 2
  • 11
  • 24
  • 1
    This just threw an error for me. `DataSource.Error: Microsoft SQL: Incorrect syntax near '?'. Must declare the scalar variable [...].` – Winch Jun 18 '18 at 13:17
3
queryString = "SELECT name FROM user WHERE id=" & Worksheets("Sheet1").Range("D4").Value
barrowc
  • 10,444
  • 1
  • 40
  • 53
  • I guess I have to do that in a VBA script, right? I dont think I could type that expression inside the SQL window. – GetFree Aug 17 '09 at 01:13
1

The SQL is somewhat like the syntax of MS SQL.

SELECT * FROM [table$] WHERE *;

It is important that the table name is ended with a $ sign and the whole thing is put into brackets. As conditions you can use any value, but so far Excel didn't allow me to use what I call "SQL Apostrophes" (´), so a column title in one word is recommended.

If you have users listed in a table called "Users", and the id is in a column titled "id" and the name in a column titled "Name", your query will look like this:

SELECT Name FROM [Users$] WHERE id = 1;

Hope this helps.

Kat Seiko
  • 125
  • 9