简体   繁体   中英

Problem running SQL query in C # .NET even though the query works in microsoft sql server management studio

I get this error:

System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'BETWEEN'.'

This is my query:

  string alertsTableCOM = "  SELECT distinct A.PM_CASE_NUMBER ,A.PM_PATIENT_NUMBER "
        +" from [VW_ER_PatientCurrentInER] A"
         +"WITH(ROWLOCK)"
         +"INNER JOIN  [NDOC] B on A.PM_CASE_NUMBER = B.FALNR"
          +"INNER JOIN [N2PMDETEXT] C"
         +"WITH(ROWLOCK)"
          +"ON C.DOKNR = B.DOKNR AND C.DOKVR = B.DOKVR"
         +"LEFT JOIN [Diagnosis_ER] E"
         +"WITH(ROWLOCK)"
         +"ON E.DOKNR = B.DOKAR and E.DOKVR = B.DOKVR"
         +"AND(SUBSTRING(E.TA_DKEY1, 1, 3) "
         +"BETWEEN @min AND @max" 
         +"OR SUBSTRING(E.TA_DKEY1, 1, 3) IN ('991', '993.4', '994.0', '994.8'))"
         +"AND ISNUMERIC(E.TA_DKEY1)= 1"
         +"AND PATINDEX('%.%',E.TA_DKEY1) = 4"
         +"WHERE CONTENT LIKE '%נפל%' OR CONTENT LIKE '%חבלה%' AND E.TA_FALNR is null; 
           ";

this is the connection and execute query

    connection.Open();
    adap = new SqlDataAdapter(alertsTableCOM, connection);
    adap.SelectCommand.Parameters.AddWithValue("@min", 800);
    adap.SelectCommand.Parameters.AddWithValue("@max", 959);
    ds = new DataSet();
    records = ds.Tables["alertsTable"];
    adap.Fill(ds, "alertsTable");
    records = ds.Tables["alertsTable"];

I tried another query and it worked..the question is how do I know what the error is? Thanks

If the query works fine in MSSQL, you can try to use Add() method instead of AddWithValue to also specify the type of passed variable.

adap = new SqlDataAdapter("YOUR SELECT STATEMENT", connection);
adap.SelectCommand.Parameters.Add(new SqlParameter
{
    ParameterName = "@min",
    Value = 800,
    SqlDbType = SqlDbType.Int
});
adap.SelectCommand.Parameters.Add(new SqlParameter
{
    ParameterName = "@max",
    Value = 959,
    SqlDbType = SqlDbType.Int
});

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