c# - Updating a column in sql with variable value -


i trying update table column using variable contains name of column instead of writing column name. how correctly can write query? i've tried

update room  set ['"+time+"']=0  day='"+day+"' 

this query showing error saying

invalid column name

although matches column name.

you, probably, looking syntax this:

  string sql =       $@"update room            set [{time}] = 0 -- time contains field's name no need in '...'          [day] = '{day}'"; 

however, hardcoding - ...'{day}'... bad practice, parametrizing right way:

  string sql =       $@"update room            set [{time}] = 0          [day] = @prm_day";    // providing use ms sql - sqlcommand   using (sqlcommand q = new sqlcommand(sql, myconnection)) {     //todo: check actual rdmbs type - sqldbtype.datetime?      q.parameters.add("@prm_day", sqldbtype.datetime).value = day;      q.executenonquery();   } 

edit: old c# versions don't support string interpolation ($ before string, see comments below), alternative formatting:

  string sql = string.format(      @"update room           set [{0}] = 0 -- time contains field's name no need in '...'         [day] = '{1}'", time, day); 

and

  string sql = string.format(       @"update room            set [{0}] = 0          [day] = @prm_day", time); 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -