Change SQL select command operator in WHERE part at runtime

98 views Asked by At

I am trying to implement user rights management in a project with C# and asp.net. What I want to do is simply showing the relevant pages to the user according to the login name. I wrote lots of SQL select commands.

Is there a way to change the WHERE part only in a SQL select command? I mean for example when a user clicks on a button

...WHERE REGION='IC' becomes ...WHERE REGION<>'IC'

Or can you please advise any other practices to implement such a scenario?

Thanks in advance

Edit: My select commands

SELECT * FROM (SELECT Firma,BOLGE,SUM(KDV_MATRAHI) AS TUTAR from SATISLAR_T WHERE DAHIL=0 AND REGION=REGION  GROUP BY Firma,BOLGE UNION SELECT Firma,CH_YETKI_KODU AS BOLGE, SUM(KDV_MATRAHI)  AS TUTAR
FROM LNX_STD_6_016_01_SLSINVOICES WHERE MALZEME_OZEL_KODU<>'DİĞER GLR'   AND REGION=REGION GROUP BY REGION, Firma) AS BOLGE
  PIVOT
(
SUM(TUTAR)
    FOR Firma IN ([008] ,[009] ,[010] ,[011], [012], [013], [014] ,[015],[016])
)AS pvt

After user clicks on the button:

SELECT * FROM (SELECT Firma,BOLGE,SUM(KDV_MATRAHI) AS TUTAR from SATISLAR_T WHERE DAHIL=0 AND REGION='IC'  GROUP BY Firma,BOLGE UNION SELECT Firma,CH_YETKI_KODU AS BOLGE, SUM(KDV_MATRAHI)  AS TUTAR
FROM LNX_STD_6_016_01_SLSINVOICES WHERE MALZEME_OZEL_KODU<>'DİĞER GLR'   AND REGION<>'IC' GROUP BY CH_YETKI_KODU, Firma) AS BOLGE
  PIVOT
(
SUM(TUTAR)
    FOR Firma IN ([008] ,[009] ,[010] ,[011], [012], [013], [014] ,[015],[016])
)AS pvt
3

There are 3 answers

3
Luiz Carlos Ciafrino Neto On

The obvious way to implement that functionality would be to have the two different queries as functions and call the appropriate ones depending on the state of the button. No clever code or tricks required.

1
JohnHC On

A quick and dirty way is to pass a parameter

where 
  ((@Param=1 and REGION = 'IC')
    or
  (@Param=2 and REGION <> 'IC'))
1
Dmitry Bychenko On

I suggest formatting when forming SQL:

// depending on condition 
// we put either REGION='IC' or REGION<>'IC' instead of {0} place holder
string sql = string.Format( 
    // Make slq readable and maintainable, use @ verbatim strings
  @"select ...
     where {0} 
     ...", condition ? "REGION='IC'" : "REGION<>'IC'"); 

using (var command = new SqlCommand(connection)) {
  command.CommandText = sql;
  ...
}

In case of C# 6.0, string interpotaion is an alternative:

string sql =  
  $@"select ...
      where {(condition ? "REGION='IC'" : "REGION<>'IC'")} 
      ...";