简体   繁体   中英

Issue checking if entry in table already exists by checking zone, date and hour

I have a database with a table in which I store several values along with the zone to which it belongs, the date it is from, and the hour it is from. The table will get updated periodically, from a source that may contain both new and old data I already have, new data will be inserted, old data I already stored will be updated, since it may have changed from the time it was created and I need the newest possible.

I have no problem checking wether the zone and the hour already exists:

sql.CommandText = "select 'Y' from dual where exists (select * from mytable where hour= "+hour+" and zone='" + zone+ "')"

But If add the date to the equation it fails when it calls the ExecuteScalar method:

sql.CommandText = "select 'Y' from dual where exists (select * from mytable where hour = " + hour + " and zone = '" + zone+ "' and date_field = '" + datevalue + "')"

I have tried other methods before but none seemed to work, like doing a Select Count(*) and executing the reader or doing a merge sentence.

Any help is appreciated. I'm working on VB, .NET framework 3.5, and Oracle 10g.

Probably the conversion from DateTime to string is in a format that the Sql server does not recognize.
You should use SqlParameter instead of concatenating a string with the values. Also make sure the values are in the correct type. ( DateTime for datevalue and not string )

using (var command = new SqlCommand("select 'Y' from dual where exists (select * from mytable where hour = @hour and zone = @zone and date_field = @datevalue)", connection))
{
  command.Parameters.Add(new SqlParameter("hour", hour));
  command.Parameters.Add(new SqlParameter("zone", zone));
  command.Parameters.Add(new SqlParameter("datevalue", datevalue));

  var reader = command.ExecuteReader();
}

This will also avoid nasty SQL injection attacks.

The comparison must look like this in oracle:

... AND date_field = TO_DATE('27-09-2012', 'DD-MM-YYYY')

Try this, if you want to keep the string version, but using a prametrized query as Magnus has shown, circumvents the date representation problem:

sql.CommandText = String.Format(@"SELECT 'Y' FROM dual WHERE EXISTS
    (SELECT * FROM mytable
     WHERE hour = {0} AND zone = {1} AND
           date_field = TO_DATE('{2:dd-MM-yyyy}','DD-MM-YYYY'))",
    hour, zone, datevalue);

Note: datevalue is assumed to be a DateTime .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM