Link to home
Start Free TrialLog in
Avatar of Brandon Garnett
Brandon Garnett

asked on

Can you send a WHERE clause from access to Microsoft SQL server

I have a screen in access where I am allowing the user to choose what they do and do not want selected from a query. I am building the WHERE clause dynamically based off of what they select. This query takes way to long to run in access, but only takes about eight seconds in Microsoft SQL server. I have created a stored procedure in SQL server and I want to pass the WHERE clause that I have built into it, but it wants the variable to be set equal to something instead of just the statement in order to prevent SQL injection attacks. I have also tried to use exec() and pass everything as a string, but i have strings in my WHERE clause which prevent the entire string from passing. ex. 'This is a example ' strVar ' that I pass'. Is there any way I can pass the information I want into SQL server?

Thanks
Avatar of PatHartman
PatHartman
Flag of United States of America image

You have to build the query in VBA so that all the variables can be expanded first.

strSQL = "Select ...., From ... WHERE ClientID = " & Me.ClientID & " AND " OrderDate > #" & Me.FromDate & "#;"
Avatar of Brandon Garnett
Brandon Garnett

ASKER

On my form I just have radio buttons, two for each choice, once to include that item, one to not include that item. I do not know what they will choose or if they will choose it. When they select something I simply add it to the WHERE clause.

WhereClause = WhereClause + "tblProject.ProjectStatus = 2"

I then just pass WhereClause into SQL server where it will hopefully run it.
Would I have to create a variable for each item on the page and pass it to SQL server?
SOLUTION
Avatar of PatHartman
PatHartman
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I was able to pass just my WHERE clause into SQL server by creating a variable in SQL server:

@SQL = 'SELECT .... FROM ... WHERE ' + @WhereClause
exec(@SQL)

But building the query in VBA and running the query as exec(@VBA) would work as well.
Looks like we have a winner here, but in case it helps I have an article called Migrating your Access Queries to SQL Server Transact-SQL that is a big honkin' comparison between Access and SQL Server T-SQL.  If it helps please click the big green 'Was this article helpful?' button at the end.