Writing dyanmic SQL in an ASP page

By Bill Graziano on 29 July 2000 | 3 Comments | Tags: Queries

Alejandro writes "Please help me, I can't write the syntax for something like this: search?cat1=America&cat2=EEUU . . . "

I can't write the syntax for something like this:


I have this:

MySQL = "SELECT * FROM MiTable WHERE cat1='" & Request.QueryString("cat1") & cat2='" & Request.QueryString("cat2") "'"


I always try to start with the results when I'm writing dynamic SQL in an ASP page. I'm guessing you want to end up with something like this:

Select *
From MiTable
Where cat1 = 'America'
and cat2 = 'EEUU'

I also try to simplify my code so that it's easier to read. When I'm building complex strings (like SQL statements) it really help to break it into multiple lines that each append to the string. Your code might look something like this:

MySQL = "SELECT * FROM MiTable "
MySQL = MySQL & " Where cat1='" & Request.QueryString("cat1") & "'"
MySQL = MySQL & " and cat2='" & Request.QueryString("cat2") & "'"

Remeber that SQL Server likes single quotes around character constants (strings) and not double quotes. Also remember to leave spaces between SQL keywords if you use this approach.

I would also be careful using Select *. This will bring back every column in a table or view. If tables change over time you might be returning values you don't need. I'd suggest you list the specific fields you want in your Select statement.

Discuss this article: 3 Comments so far. Print this Article.

If you like this article you can sign up for our weekly newsletter. There's an opt-out link at the bottom of each newsletter so it's easy to unsubscribe at any time.

Email Address:

Related Articles

Using Dynamic SQL in Stored Procedures (7 March 2011)

Joining to the Next Sequential Row (2 April 2008)

Writing Outer Joins in T-SQL (11 February 2008)

Aggregating Correlated Sub-Queries (23 October 2007)

How to Use GROUP BY with Distinct Aggregates and Derived tables (31 July 2007)

How to Use GROUP BY in SQL Server (30 July 2007)

Returning Complex Data from User-Defined Functions with CROSS APPLY (11 June 2007)

Returning a week number for any given date and starting fiscal month (2 May 2007)

Other Recent Forum Posts

How to Download Ringtones (1 Reply)

Database Diagram not showing relationship of table (3 Replies)

SQL2008R2: Should there be a limit xmla qry size? (3 Replies)

Variables in Where Clause (20 Replies)

how to update 2 records on 1 field (20 Replies)

How to migrate Replication DB on sql server 2008 (7 Replies)

Reading XML in SQL (5 Replies)

Return a zero value in place of null (8 Replies)

Subscribe to SQLTeam.com

Weekly SQL Server newsletter with articles, forum posts, and blog posts via email. Subscribers receive our white paper with performance tips for developers.

SQLTeam.com Articles via RSS

SQLTeam.com Weblog via RSS

- Advertisement -