Click here to Skip to main content
15,885,842 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Hi everyone!

I am running into an issue that I need some advice on. I am using parametrized queries to get information from chosen items in comboboxes to place in the queries for further down.

The idea that I have right now is:

Combobox 1 - get table name
Combobox 2 - get column name

Query to grab selected column name for the next combobox.

The query that I'm stuck on is:

SQL
SqlCeCommand accessoriesCommand = new SqlCeCommand("SELECT DISTINCT subcategory FROM accessories WHERE subcategory = @subcategory", conn);


The table in this query doesn't have a column called "subcategory". The selected item in the combobox 2 is supposed to be placed in the accessoriesCommand. Is this do-able? If so, can someone shed some light as to how to properly format this?

The error I'm getting is that the column doesn't exist.

Thanks everyone!
Posted
Comments
Richard C Bishop 15-Feb-13 12:34pm    
So wouldn't you want to have the actual name of the table column in your query and the selection from the combobox would be your variable that the Where clause checks for?
joshrduncan2012 15-Feb-13 12:38pm    
My boss wants me to allow for dynamic column looping through from information_schema.columns incase our client wants to add a new subcategory. The subcategories are the columns in some of the tables. I really prefer parametrized queries, but I have to manually prevent sql injection (per Griff's answer below.)
Richard C Bishop 15-Feb-13 12:40pm    
Got ya.
joshrduncan2012 15-Feb-13 12:41pm    
Even though it drives me crazy that I can't use parametrized queries in this instance, I am ok with it. Manual SQL injection prevention is next on my radar to catch up on.

You can't pass the name of the column as a parameter - you would have to concatenate strings to create the command (and be very careful to protect yourself from SQL injection attacks):
C#
SqlCeCommand accessoriesCommand = new SqlCeCommand("SELECT DISTINCT " + subcategory  + " FROM accessories", conn);
 
Share this answer
 
Comments
joshrduncan2012 15-Feb-13 12:34pm    
Thanks Griff!
OriginalGriff 15-Feb-13 12:40pm    
You're welcome!
Richard C Bishop 15-Feb-13 12:40pm    
Nice job OG.
Monjurul Habib 17-Feb-13 6:24am    
5+
Might something like the following be useful?

SELECT 'SELECT DISTINCT '+[2]+' FROM '+[1] FROM __sysobjects WHERE [1]=@TableName AND [2]=@ColumnName

If the table and column exists you should get a result which you can then execute.
 
Share this answer
 
Comments
joshrduncan2012 15-Feb-13 14:19pm    
Another GREAT solution. Thanks PIEBAL.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900