I am migrating some code from ColdFusion to .NET LinqToSQL. The following query is currently embedded into ColdFusion. Rather than trying to get LinqToSQL to this, I am considering writing a stored procedure. Note: the ## in CF in this context is really a # in SQL. I am not creating a global temp table
<cfquery name="qryTrafficDetails">
DECLARE @startDate date
DECLARE @endDate date
SET @startDate = <cfqueryparam cfsqltype="CF_SQL_date" value="#filter.StartDate#">
SET @endDate = <cfqueryparam cfsqltype="CF_SQL_date" value="#filter.endDate#">
SELECT CONVERT(date, CreateDate) AS CreateDate, url_vars.value('(search)[1]', 'nvarchar(max)') AS Item, remote_addr
INTO ##tempTraffic
FROM dbo.Traffic WITH (NOLOCK)
WHERE Createdate BETWEEN @startDate AND @endDate
AND url_vars.exist('.[search]') = 1
SELECT Area, AreaSort, Item, CalendarDate, isNull(Visitor, 0) AS Visitor, ISNULL(Hit,0) AS Hit
FROM dbo.Calendar LEFT JOIN
(
SELECT AreaSort = 10, 'Search' AS Area, FullGrid.Item AS Item, FullGrid.CalendarDate AS CreateDate,
COUNT(DISTINCT remote_addr) AS visitor,
COUNT(remote_addr) as hit
FROM (
SELECT DISTINCT CalendarDate, Item
FROM dbo.Calendar, ##TempTraffic
WHERE CalendarDate BETWEEN @startDate AND @endDate
) FullGrid
LEFT JOIN ##TempTraffic AS DataItem
ON FullGrid.CalendarDate = CreateDate
AND FullGrid.Item = DataItem.Item
GROUP BY FullGrid.Item, FullGrid.CalendarDate
) AS SummaryDetail
ON CalendarDate = SummaryDetail.CreateDate
WHERE CalendarDate BETWEEN @startDate AND @endDate
AND AreaSort IS NOT NULL
ORDER BY AreaSort, Item, CalendarDate
</cfquery>
<cfreturn qryTrafficDetails>
Some of the issues I am concerned with are:
- How to deal with temp tables
- Does LinqToSql cover everything?
- Is this an example of where LinqToSql is not appropriate?
- Performance
I’m not completely sure about the intentions and motivations of your sql code but seems to be a summary report. In this case probably linq to sql is not the ideal solution.
I don’t think that you can create temp table from linq 2 sql. You can create sub query or maybe you can use linq 2 object to join the results of previously executed query.
But my suggestion is to check if there isn’t a better way to query your data using a more concise query that can be executed also on linq 2 sql.
If you really need this kind of query probably it’s better to put it in a stored procedure.