views:

98

answers:

1

I would like to build the where clase of a sql statement dynamically from hashtable in C#.

The key of the hash_table will be the column's name to be inserted and the value of hash_table will be value.

string sql_1="SELECT COL_1,COL_2 FROM MY_TABLE";
string sql_2="SELECT * FROM MY_TABLE WHERE COL_3='ABC'";  //note: some statment have where clause while some do NOT have. 

string sql= ToSql(sql_1,myHashTable); // the actual sql statment will be returned from ToSql
//execute sql
sql= ToSql(sql_2,myHashTable); // 
//execute sql

My Question is, how can I create function ToSql() function in LINQ?

NOTE: The data type of the value of hashtable will be taken into consideration.

Thanks in advance.

+3  A: 
var q = String.Join(" AND ", myHashTable.Select(x => x.Key.ToString() + " = " + 
    (x.Value is string ? "'" : "") + x.Value.ToString() + 
    (x.Value is string ? "'" : "")))

Of course you're going to have to decide whether to add a "WHERE", "AND", have to strip off some "GROUP BY" clause first before adding "WHERE", and deal with escaping, but I trust you can handle that.

However, I would strongly suggest using parameterized queries instead, and add the parameters to the SqlCommand. Something like:

var q = String.Join(" AND ", myHashTable.Select(x => x.Key.ToString() + " = @" +
    x.Key.ToString()));

var parameters = myHashTable.Select(x => new SqlParameter("@" + x.Key.ToString(), 
    x.Value));
lc
Thanks for suggestion. But,I think, using parameterized queries is not possible for me because ,the number of parameters will be passed can be known only at runtime,which will needs some extra codes.By the way,is it possible to access Hashtable in LINQ?
Kai
@Kai, the parameterized query is still a custom-at-runtime query; it just saves you the hassle of trying to correctly escape the parameters, which is a Very Valuable security technique.
Craig Trader
@W.Craig Trader ,Thanks for correcting me.But, I have already had the function that can handle this ,and I need to pass just the sql statement to this.
Kai