La risposta breve è che è necessario inserire il carattere jolly nel valore del parametro, non nel CommandText. cioè
non
che: sqlCommand.CommandText = "SELECT * FROM JOB WHERE JOB_POSTCODE LIKE @postcode%"
questo:
sqlCommand.CommandText = "SELECT * FROM JOB WHERE JOB_POSTCODE LIKE @postcode";
sqlCommand.Parameters.Add("@postcode", SqlDbType.NVarChar).Value = postCode + "%";
Risposta lunga qui:
sono tornato e messo a nudo il mio codice verso il basso per gli elementi essenziali in modo che potessi postare qui, e mentre lo facevo ho scoperto che l'ultimo metodo che ho provato nella mia domanda originale funziona davvero. Deve essere stato qualcosa di sbagliato nei miei test. Quindi, ecco una sintesi, con il codice che è stato eseguito:
SQL dinamico originale, vulnerabile a SQL injection:
//Dynamic sql works, returns 2 results as expected,
//but I want to use parameters to protect against sql injection
string postCode = "G20";
sqlCommand.CommandText = "SELECT * FROM JOB WHERE JOB_POSTCODE LIKE '"
+ postCode + "%'";
return Database.fGetDataSet(sqlCommand,
iiStartRecord,
iiMaxRecords,
"JOBVISIT");
Primo tentativo di utilizzare il parametro dà un errore:
//This syntax with a parameter gives me an error
//(note that I've added the NVarChar length as suggested:
//System.FormatException : @postcode : G20 -
//Input string was not in a correct format.
//at System.Data.SqlServerCe.SqlCeCommand.FillParameterDataBindings()
//at System.Data.SqlServerCe.SqlCeCommand.ExecuteCommandText(IntPtr& pCursor,
// Boolean& isBaseTableCursor)
string postCode = "G20";
sqlCommand.CommandText = "SELECT * FROM JOB WHERE JOB_POSTCODE LIKE @postcode
+ '%'";
sqlCommand.Parameters.Add("@postcode",
SqlDbType.NVarChar,
10).Value = postCode;
return Database.fGetDataSet(sqlCommand, iiStartRecord, iiMaxRecords, "JOBVISIT");
La seconda tecnica funziona effettivamente:
///This syntax with a parameter works, returns 2 results as expected
string postCode = "G20";
sqlCommand.CommandText = "SELECT * FROM JOB WHERE JOB_POSTCODE LIKE @postcode";
sqlCommand.Parameters.Add("@postcode", SqlDbType.NVarChar).Value = postCode
+ "%";
return Database.fGetDataSet(sqlCommand, iiStartRecord, iiMaxRecords, "JOBVISIT");
Grazie per tutti gli input, e mi dispiace per la domanda fuorviante originale ...
query full: @ "SELECT * FROM JOB WHERE DELETED = false AND JOB_POSTCODE LIKE '" + isPostCode +'% '" – Colin