SQL concatenating in C#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Radu
    New Member
    • Apr 2011
    • 2

    SQL concatenating in C#

    Hello,
    I have a table in a data base named Table (access data base), with the following fields:
    Name - string
    TheaterNr - number
    Day - date/time

    and i`m trying to store in an OleDbCommand X.Command an sql statement:

    X.Command = "SELECT Name, TheaterNr, Day FROM Table WHERE Name = <name of a variable that stores a string> AND TheaterNr = <name of a variable that stores a number> AND Day = <name of a variable that stores a date/time>"

    I`m lost among all the ' " and i don`t know how to use the CAST function as i think it`s necessary for the parsing of the number and date/time variables.
    I hope you can help me :)
  • Alex Dransfield
    New Member
    • Jan 2011
    • 46

    #2
    Here's an example of an SQL string that i've concatenated in my program.

    Code:
    "SELECT code, moduletitle, body, timeofday, duration, examdate FROM EXAMDAT WHERE examdate BETWEEN #01/05/2011# AND #09/04/2022# AND body='OCR';"
    As you can see at the WHERE statement, I have used sinle quotes around the string I want to look for.

    Code:
    "SELECT code, moduletitle, body, timeofday, duration, examdate FROM EXAMDAT WHERE examdate BETWEEN #" + fromDate + "# AND #" + toDate + "# AND body='OCR';";
    And here's what the string was made from

    Comment

    • adriancs
      New Member
      • Apr 2011
      • 122

      #3
      try this:
      Code:
      string name = "John";
      int theaterno = 1;
      string date = string.Format("{0:yyyy-MM-dd}", DateTime.Now);
      X.Command = string.Format("SELECT Name, TheaterNr, Day FROM Table WHERE Name = '{0}' AND TheaterNr = '{1}' AND Day = '{2}'",name, theaterno, date);

      Comment

      • Radu
        New Member
        • Apr 2011
        • 2

        #4
        Thank you. Your answers helped and i`ve figuered it out eventualy.

        Comment

        Working...