1

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

2 Answers 2

3

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()
             };
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.