views:

75

answers:

3

I have a Stored Procedure which executes some dynamic SQL. I want to use this Stored Procedure in entity framework 4, but when I try to create a complex type the procedure returns no columns. Is there any way I can force it to return my values and get the entity framework to receive them? Here is a much-simplified example of what I want to do:

CREATE PROCEDURE sp_calculatesalary(@EmployeeId as int)
begin
    declare dynsql as varachar(500)
    @dynsql='Select @Salary=Salary,@UserName=Username from employee
            where EmployeeId='+cast(@EmployeeId as varchar)+ ''
    exec(@dynsql)
    select @Salary, @UserName
end

But this does not work. Please help me out. Basically, I want to use a Stored Procedure to execute dynamic SQL and return the values to the entity framework.

+3  A: 

Perhaps you could consider parameterized SQL, if you must do dynamic queries:

CREATE PROCEDURE sp_calculatesalary(@EmployeeId as int)   
begin   
declare @dynsql varchar(500)   
declare @params nvarchar(500)
declare @salary money
declare @username varchar(50)
@dynsql='Select @sal=Salary,@usernm=Username from employee where EmployeeId=@empID'   
@params='@empID int, @sal money OUTPUT, @usernm varchar(50) OUTPUT'
exec sp_executesql @dynsql, @params, @empID=@EmployeeID, @sal=@salary OUTPUT, @usernm = @username OUTPUT
SELECT @salary, @username
Strommy
That is how I had it without scalar values...but entity framework didnt detect that it returned any columns....
Misnomer
Then perhaps you could post a little more info on why you need to do it dynamically. Usually there's a way to do this without dynamic SQL.
Strommy
I have multiple where clauses...that get appended to the main select...when i pass according parameters...So using dynamic sql to build those where clauses...but really all i want to know is to return values explicitly so that ef4 recognizes it...
Misnomer
In that case, the above edit should get you what you want. I just like to highlight best practices to prevent SQL injection.
Strommy
Thanks it worked...will keep in mind the practices..:)..STACKOVERFLOW JUST ROCKS!!!
Misnomer
A: 

have you tried giving aliases to your last Select:

select @Salary as Salary, @UserName as UserName
Moose
tried..it...does not work...
Misnomer
A: 

Well, if EF cannot recognize what your stored procedure must return then create your complex type ahead of time. You can create a complex type by right clicking any where on the model and and add a complex type. Next when you import your stored procedure, you can choose your complex type from the dropdown.

zeeshanhirani

related questions