Question

I have the following query :

 public static DataTable GetTasks(int empNum)
        {
                StringBuilder cmdTxt = new StringBuilder();
                Dictionary<string, string> paramList = new Dictionary<string, string>();
                cmdTxt.Append(" SELECT DISTINCT a.task_code, a.task_name ");
                cmdTxt.Append(" FROM rr2_task a, rr2_task_state b, rr2state_user c ");
                cmdTxt.Append(" WHERE a.task_code= b.task_code ");
                cmdTxt.Append(" AND b.state_code= c.state_code ");
                cmdTxt.Append(" AND c.emp_num = ? ");
                cmdTxt.Append(" AND b.new_flag= 1 ");
                cmdTxt.Append(" UNION SELECT DISTINCT a.task_code, a.task_name FROM rr2_task a , rr2_candidate b ");
                cmdTxt.Append(" WHERE empnum_candidate = ? ");
                cmdTxt.Append(" AND a.task_code = b.task_code ");
                cmdTxt.Append(" UNION SELECT DISTINCT a.task_code, a.task_name FROM rr2_task a, rr2_taskstate b, rr2_stategroup c ");
                cmdTxt.Append(" WHERE a.task_code= b.task_code ");
                cmdTxt.Append(" AND b.state_code= c.state_code ");
                cmdTxt.Append(" AND ((( c.group_type = 1 ) AND ( c.group_code = (SELECT x.degree_code FROM kk2_degree_infor x WHERE x.emp_num = ? ");
                cmdTxt.Append(" AND x.degree_date = ( SELECT MAX(xx.degree_date) FROM kk2_degree_infor xx WHERE xx.emp_num = x.emp_num )))) ");
                cmdTxt.Append(" OR (( c.group_type = 2 ) AND ( c.group_code =  ( SELECT y.title_code FROM hetjob y WHERE y.emp_num = ? ");
                cmdTxt.Append(" AND y.title_date = ( SELECT MAX(yy.title_date) FROM hetjob yy WHERE yy.emp_num = y.emp_num ))))) ");

Now should I add four parameters with different names although it's actually a one param with the same value ? empNum

Was it helpful?

Solution

Well currently you're using positional parameters (?) rather than named parameters (@empnum). You haven't told us what database you're using, but I'd expect that if you can use named parameters, you could use the same name everywhere and just add a single value.

With positional parameters, you would have to provide a value for each placeholder, as there's no way of tying separate ones together.

OTHER TIPS

First of all, use @ to create a multi-line string

string sql = @"SELECT ...
FROM...
WHERE...";

to avoid some mess :)

Regarding your question, if using OleDB provider with anonymous parameters, declare a variable with such a value, then reference to it:

DECLARE @par int; --or char or whatever else
SET @par = ?

SELECT ...
FROM ...
WHERE x = @par
AND y = @par

This way, you should be able to pass the parameter only once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top