c# - NULL value checking -


i trying run following code error occurin says have error near @tid. parameter supposed taking null value.

 public static datatable getchapterarticlessummary(long chapterid, long? topicid) {     datatable tablearticles = new datatable();     try {         using (sqlconnection connection = connectionmanager.getconnection())         {             sqlcommand command = new sqlcommand();             command.commandtext = "select article_name, id, privacy_term articles chapter_id=@chapterid , topic_id @topicid";             command.parameters.add("@chapterid", sqldbtype.bigint).value = chapterid;             if (topicid != null)             {                 command.parameters.add("@topicid", sqldbtype.bigint).value = topicid;             }             else             {                 command.parameters.add("@topicid", sqldbtype.bigint).value = dbnull.value;             }             command.connection = connection;             sqldataadapter adapter = new sqldataadapter();             adapter.selectcommand = command;             adapter.fill(tablearticles);         }     }     catch (sqlexception ex)     { }     return tablearticles; } 

there 2 ways handle this:

  1. rewrite sql
  2. rewrite entire code

1. rewrite sql

change relevant portion of sql this:

and (t_id = @tid or @tid null) 

2. rewrite entire code

this result in 2 different sql statements depending on parameter (to code) value:

sqlcommand command = new sqlcommand(); if (tid != null) {     command.commandtext = "select article_name, id, privacy_term articles id=@id , t_id = @tid";     command.parameters.add("@tid", sqldbtype.bigint).value = tid; } else {     command.commandtext = "select article_name, id, privacy_term articles id=@id , t_id null"; } command.parameters.add("@id", sqldbtype.bigint).value = id; command.connection = connection; sqldataadapter adapter = new sqldataadapter(); adapter.selectcommand = command; adapter.fill(tablearticles); 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -