Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct syntax for using Database.ExecuteSqlCommand with parameters?

I use Entity Framework 4.2 and want to call a stored procedure that has input parameters. I'm using Database.ExecuteSqlCommand to call the stored procedure.

However, the documentation is lacking in the correct syntax for the call in order to map the parameters correctly. My google-foo is failing me, and any help will be appreciated.

I.e. I have a procedure

procedure SetElementFrequency
  @ElementTypeID integer,
  @Frequency float
as ...

I've tried calling it with

Database.ExecuteSqlCommand("exec SetElementFrequency @p0 @p1", 
                            elementType, frequency);

and

Database.ExecuteSqlCommand("exec SetElementFrequency {0} {1}", 
                            elementType, frequency);

but they both fail with the error Incorrect syntax near '@p1'.

like image 387
SWeko Avatar asked Jun 20 '12 14:06

SWeko


People also ask

When executing a command parameters must be?

When executing a command, parameters must be exclusively database parameters or values.

What is execute SQL command?

ExecuteSqlCommand(TransactionalBehavior, String, Object[]) Executes the given DDL/DML command against the database. As with any API that accepts SQL it is important to parameterize any user input to protect against a SQL injection attack.


1 Answers

Depending on your underlying database provider, you can use either of the following.

Database.ExecuteSqlCommand(
    "exec SetElementFrequency {0}, {1}",
    elementType, frequency); 

or

Database.ExecuteSqlCommand("exec SetElementFrequency ?, ?", elementType, frequency); 

You may also specify elementType and frequency as DbParameter-based objects to provide your own names via the ParameterName property.

like image 90
bricelam Avatar answered Sep 30 '22 14:09

bricelam