So I need some with a sql query. The sql generated from linq is very subpar it seems and the stored procedure times out.
Here's what i'm trying to do.
Two tables, look like this:
dbo.Links
-------------
Id
Url
Title
And another one that looks like this
dbo.Link_Counts
-----------------
Url
Count
What I would like to do is write a sql query that does this
var linkCounts = Links.GroupBy(x => x.Url)
.Select(grp => new Link_Counts
{
Url = grp.First().Url,
Count = grp.Count()
});
InsertAllOnSubmit(linkCounts);
SubmitChanges();
The sql that I attempted to use that is partly generated from this is
INSERT INTO Link_Counts (Url, Count)
SELECT (
SELECT [t3].[URL]
FROM (
SELECT TOP (1) [t2].[URL]
FROM [Links] AS [t2]
WHERE (([t1].[URL] IS NULL) AND ([t2].[URL] IS NULL)) OR (([t1].[URL] IS NOT NULL) AND ([t2].[URL] IS NOT NULL) AND ([t1].[URL] = [t2].[URL]))
) AS [t3]
) AS [Url], [t1].[value] AS [Count]
FROM (
SELECT COUNT(*) AS [value], [t0].[URL]
FROM [Links] AS [t0]
GROUP BY [t0].[URL]
) AS [t1]
END
Where apparently is too long running for a stored procedure.
Any help would be greatful.
Thanks
If you want to write the SQL by hand:
insert into link_counts (url, count)
select url, count(0)
from links
group by url
Or, if you just want to fix the LINQ query to generate better SQL:
var linkCounts =
Links.GroupBy(x => x.Url)
.Select(g => new Link_Counts
{
Url = g.Key,
Count = g.Count()
};
I think this is what you need to insert the count for each url:
insert into Link_Counts (Url, Count)
select Url, Count(*)
from dbo.Links
group by Url
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.