Stored Proc that has output values - stored-procedures

I need to create a stored proc that will return records (more than one record). I would like to return back AccountID, FirstName, LastName & email.
For example, I am comparing two tables using the AccountID fields.
So currently my query is:
Select AccountID, FirstName, LastName, email
from tblCustomers
Where AccountID not in
(select AccountID from tblVendors)

Not sure what your question here is...but you could create that procedure with
CREATE PROCEDURE dbo.spGetNonVendors
AS
BEGIN
Select AccountID, FirstName, LastName, email
from tblCustomers Where AccountID not in (select AccountID from tblVendors)
END
See here for syntax for created stored procedures:
http://msdn.microsoft.com/en-us/library/ms187926.aspx
As for how to get the output, you should know there are actually three different sources of output from a stored procedure:
Output parameters
Result sets
Messages
If you look at the docs on the page I referenced, you'll see how to declare output variables. Those are good for single values, but not what you're looking for here.
Result sets are just any select statement you happen to run while in the procedure. As you've seen from the answers here, there's nothing special to do, just execute the select.
Finally, the message output contains error messages, print statements, etc.
Now how you get to your select output depends on your client. How are you connecting to sql server and executing the procedure? If you're using Sql Management studio, you'll see the two tabs for result sets and messages. If you're using C#, a SqlDataAdapter or SqlDataReader will automatically be reading from your result sets.

you just do as may select statements as you need within the Stored Procedure then depending on what language you are using you can loop through the result sets to get the data.
hope that helps,
Josh

CREATE PROCEDURE Procedurename
AS
BEGIN
Select AccountID, FirstName, LastName, email
from tblCustomers
where AccountID not in (select AccountID from tblVendors)
END

So, just put it in a procedure:
create procedure CompareCustomers
as
select AccountID, FirstName, LastName, email
from tblCustomers
where AccountID not in (select AccountID from tblVendors)
I would however prefer a join over "not in":
create procedure CompareCustomers
as
select c.AccountID, c.FirstName, c.LastName, c.email
from tblCustomers c
left join tblVendors v on v.AccountID = c.AccountID
where v.AccountID is null

Related

ASP.NET MVC controller join two tables: "An anonymous type cannot have multiple properties with the same name"

I have the following code to join two tables in an ASP.NET MVC controller but I also want to display employee's supervisor name from the same table and same filed.
But I get an error:
An anonymous type cannot have multiple properties with the same name
Here is my code
public IHttpActionResult GetEmployees()
{
var query = (from n in db.Employees
join c in db.tblCities on n.ProjectID equals c.CityID
into nc
from c in nc.DefaultIfEmpty()
join manager in db.Employees on n.ManagerName equals manager.Name
into pc
from managerin pc.DefaultIfEmpty()
select new
{
n.Name,
manager.Name,
n.Email,
c.CityName
});
var employees = query.ToList();
return Ok(employees);
}
What is the workaround to accomplish my goal?
You need to give the properties (or at least conflicting ones) actual names so you know what is what. Which Name would be Name if you don’t? For example:
select new
{
n.Name
ManagerName = manager.Name,
n.Email,
c.CityName
}
Also often it’s better to use actual types instead of anonymous ones so you get type safety properly through the application, especially when this information is given out to views etc.

Get TFS Query GUID

I am using some existing code in a project where some code is querying using a GUID to get list of WorkItems from a query ( as list of blocking bugs etc.) using a query name and GUID.
var items = project.Store.GetQueryDefinition(queryGUID);
Question : for a given TFS query how can I get its GUID ?

MVC Stored procedure calling

Since this question created a lot of confusion let me put in this way :
I am working on an MVC C# project with Entity Framework. I am using a web service to implement a billing feature. Here I am passing values like this:
Billing.cost bills = new Billing.cost();
bills.Charge(0,"model",8,0,"Date",0,1,1,1,0,0,"N","APP","myemail",1,"cost");
Here in place of a model I need to pass my stored procedure name which has required values. My complete code with Stored procedure :
using (var ctx = new market_Entities())
{
ctx.uspmodel(10);
ctx.SaveChanges();
Billing.cost bills = new Billing.cost();
bills.Charge(0,"ctx",8,0,"Date",0,1,1,1,0,0,"N","APP","myemail",1,"cost");
}
Here 10 is an ID which i am passing as an input parameter. In charge method, 2nd parameter that is ctx is of string type and it is reference to my SP.
Problem I have is :
1) My stored procedure doesn't have output parameter.It is taking id as input parameter and based on that it is selecting name, value and address. So in place of ctx, I need to pass address result which I am getting from my stored procedure. But how can I select only particular property from market_entities and pass it as parameter ?
2) when I put breakpoints and check for results, I am not able to see any results.So how can i check results for a stored procedure in MVC which doesn't have output parameters?

Error in breeze using EF 5 and calling stored procedure

Getting an error client side with breeze: "Cannot call method 'map' of undefined" when trying to pull over some data. The difference between this action and one that works is that this action is calling a stored procedure and returning ObjectResult<T> instead of DbSet<T>.
Might this be why I get an error? Using Chrome Developer tools, I do see that the breeze controller is returning json data.
I have created a complex model type in the edmx for mapping the rows returned from the stored procedure.
The action in the breeze controller has a return type of IEnumerable<T>.
I experienced the same error when using an EF complex type. A workaround was to create a view in my database instead of using a complex type, set the stored procedure to return a type of the new view which had a primary key and then it worked. It would seem that breeze requires entities to have a primary key defined.
Hm... not quite sure what is happening, so just guessing here, but try adding an AsQueryable() to the result returned, and changing the result type to a IQueryable.
We don't have any stored proc tests for breeze yet, but this is impetus for me to add some :)
I had the very same issue, but thank God I figured out a solution. Instead of using a stored procedure, you should use a view, as Breeze recognizes views as DbSet<T>, just like tables. Say you have a SQL server table that contains two tables Customers and Orders.
Customers (**CustomerId**, FirstName, LastName)
Orders (OrderId, #CustomerId, OrderDate, OrderTotal)
Now, say you want a query that returns orders by CustomerId. Usually, you would do that in a stored procedure, but as I said, you need to use a view instead. So the query will look like this in the view.
Select o.OrderId, c.CustomerId, o.OrderDate, o.OrderTotal
from dbo.Orders o inner join dbo.Customers c on c.CustomerId = o.CustomerId
Notice there is no filtering (where ...). So:
i. Create a [general] view that includes the filtering key(s) and name it, say, OrdersByCustomers
ii. Add the OrdersByCustomers view to the entity model in your VS project
iii. Add the entity to the Breeze controller, as such:
public IQueryable<OrdersByCustomers> OrdersByCustomerId(int id)
{
return _contextProvider.Context.OrdersByCustomers
.Where(r => r.CustomerId == id);
}
Notice the .Where(r => r.CustomerId == id) filter. We could do it in the data service file, but because we want the user to see only his personal data, we need to filter from the server so it only returns his data.
iv. Now, that the entity is set in the controller, you may invoke it in the data service file, as such:
var getOrdersByCustomerId = function(orderObservable, id)
{
var query = breeze.EntityQuery.from('OrdersByCustomerId')
.WithParameters({ CustomerId: id });
return manager.executeQuery(query)
.then(function(data) {
if (orderObservable) orderObservable(data.results);
}
.fail(function(e) {
logError('Retrieve Data Failed');
}
}
v. You probably know what to do next from here.
Hope it helps.

Linq to Entities: How to pass a parameter to a string Contains method within a join?

Basically, this works:
from membershipUser in context.MembershipUsers
join user in context.Users on membershipUser.UserName equals (user.UserName.Contains("partner:") ? user.UserName.Replace("partner:", "") : user.UserName)
But this doesn't:
var usernamePrefix = "partner:";
...
from membershipUser in context.MembershipUsers
join user in context.Users on membershipUser.UserName equals (user.UserName.Contains(usernamePrefix) ? user.UserName.Replace(usernamePrefix, "") : user.UserName
I keep getting a timeout exception.
The only difference in the generated SQL scripts is that the first one renders:
LIKE N'%partner:%'
While the latter renders:
LIKE '%partner:%' /* #p__linq__3 */ ESCAPE N'~'
(Both SQL scripts work when run in the Management Studio)
Any thoughts?
(UPDATE: I've seen that with a small number of rows both ways work, but when I hit more than 1000 rows I get the timeout exception)
L2E always uses a SQL param with non-constant values for security against SQL injection attacks.
As you've seen, however, the DB server can't always optimize parameterized queries as well.
However, Entity SQL has no such restriction, so you can write an ESQL query.
Alternately, map a proc, view, or use ObjectContext.ExecuteStoreCommand.
You can also change the DB schema to store a directly compare-able value.
By the way, I consider mapping the ASP.NET membership tables to be a bad idea.
Edit: One more thing to try...
from membershipUser in context.MembershipUsers
from user in context.Users
where membershipUser.UserName == user.UserName
|| membershipUser.UserName == usernamePrefix + user.UserName
select ...

Resources