简体   繁体   中英

C# SQL statement - Syntax error in query. Incomplete query clause

Below is the code I have, I can't for the life of me work out what is wrong with the query.

I originally had the error "no value given for 1 or more parameters", which seems to have gone away (although again I don't even know why I was getting it).

The connection is opened prior to this code. The parameter GVars.thisFY is a string = "FY13" - this table definitely exists. The parameter GVars.currentDate is a DateTime = today.

Records definitely exist for this [Destination] and [Next Collection] range:

string sql;
OleDbDataAdapter adapter;

sql = "SELECT * FROM @CurFY WHERE [Destination] = @Destination AND [Next Collection] BETWEEN @NextCollectionA AND @NextCollectionB;";

// Create the command object
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;

// Add values to the fields
cmd.Parameters.AddWithValue("@CurFY", GVars.thisFY);
cmd.Parameters.AddWithValue("@Destination", "Henwood");
cmd.Parameters.AddWithValue("@NextCollectionA", GVars.currentDate);
cmd.Parameters.AddWithValue("@NextCollectionB", GVars.currentDate.AddDays(1));

adapter = new OleDbDataAdapter(cmd.CommandText, conn);

try
{
    adapter.Fill(ds);

    GVars.bLblLastUpdate = DateTime.Now.ToString("HH:mm:ss");
}
catch (Exception ex)
{
}

EDIT: I have changed the code to remove the table parameter as below, still getting the "no value given for 1 or more parameters" though which I can't pin down..

EDIT2: I removed the extra stuff so the post relates only to the original question, which has been answered. I will make a new question for my strange "no value given" error

You cannot parameterize queries with names of tables, views, or columns. Only data members can be parameterized.

You need to make your SQL dynamically, eg like this:

sql = string.Format(
    "SELECT * FROM {0} WHERE [Destination] = @Destination AND [Next Collection] BETWEEN @NextCollectionA AND @NextCollectionB;"
,  GVars.thisFY
);

This should be done only if GVars.thisFY is controlled by your code, eg comes from a pre-defined list or checked for absence of non-alphanumeric characters to avoid SQL injection attacks .

Try this one -

sql = Sring.Format(
    "SELECT * FROM {0} WHERE [Destination] = @Destination AND [Next Collection] BETWEEN @NextCollectionA AND @NextCollectionB;", 
    GVars.thisFY
)

cmd.Parameters.AddWithValue("@Destination", "Henwood");
cmd.Parameters.AddWithValue("@NextCollectionA", GVars.currentDate);
cmd.Parameters.AddWithValue("@NextCollectionB", GVars.currentDate.AddDays(1));

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