When you construct the query to the table departmentsgroupings
, you're changing the value of sql
, but you aren't creating a new SqlCommand
. This means that cmd
still contains the old SQL statement (the query to the Modules
table) which, when executed, returns "ad"
.
To fix this, change your code as follows:
sql = ("select departmentsid from departmentsgroupings where groupingid =" & pageid & "")
Set cmd = New SqlCommand(sql, conn)
did = (cmd.ExecuteScalar)
You may have expected the change you made to sql
to get passed on automatically to the SqlCommand
-- but it doesn't work that way.
Edit: Your code, as written, is vulnerable to SQL injection attacks. If you don't know what these are, you need to read the first answer to this:
How does the SQL injection from the "Bobby Tables" XKCD comic work?
To protect yourself against these kinds of attacks, use parameterized queries.