code_junkie

Accessing dynamically created stored procedure from LINQ

Nov 12th, 2011
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. CREATE PROCEDURE [dbo].[proc_StatsDay] @columns NVARCHAR(64) AS
  2.  
  3. DECLARE @SQL_PVT1 NVARCHAR(512), @SQL_PVT2 NVARCHAR(512), @SQL_FULL NVARCHAR(4000);
  4.  
  5. SET @SQL_PVT1 = 'SELECT OrderTime, ' + LEFT(@columns,LEN(@columns)-1) +'
  6. FROM (SELECT ES.Location, CONVERT(varchar(10), ES.OrderTime, 120),ES.Charge
  7. FROM dbo.log_sales ES
  8. ) AS D (Location,OrderTime,Charge)
  9. PIVOT (SUM (D.Charge) FOR D.Location IN
  10. (';
  11. SET @SQL_PVT2 = ') )AS PVT
  12. ORDER BY OrderTime DESC';
  13.  
  14. SET @SQL_FULL = @SQL_PVT1 + LEFT(@columns,LEN(@columns)-1) +
  15. @SQL_PVT2;
  16.  
  17. EXEC sp_executesql @SQL_FULL, N'@columns NVARCHAR(64)',@columns = @columns
  18.  
  19. public class DynamicResult
  20. {
  21. public DateTime OrderDate {get;set;}
  22. public decimal? Location1 {get;set;}
  23. public decimal? Location2 {get;set;}
  24. //..
  25. public decimal? Location100 {get;set;}
  26. }
  27.  
  28. IEnumerable<DynamicResult> result =
  29. myDataContext.ExecuteQuery<DynamicResult>(commandString, param1);
  30.  
  31. SELECT ES.Location, DateAdd(dd, DateDiff(dd, 0, ES.OrderTime), 0),ES.Charge
  32. FROM dbo.log_sales ES
  33.  
  34. public class LogSale
  35. {
  36. public string Location {get;set;}
  37. public DateTime OrderDate {get;set;}
  38. public decimal Charge {get;set;}
  39. }
  40.  
  41. List<LogSale> source = LoadData();
  42. var pivot = source
  43. .GroupBy(ls => ls.OrderDate)
  44. .OrderBy(g => g.Key)
  45. .Select(g => new {
  46. Date = g.Key,
  47. Details = g
  48. .GroupBy(ls => ls.Location)
  49. .Select(loc => new {
  50. Location = loc.Key,
  51. Amount = loc.Sum(ls => ls.Charge)
  52. })
  53. });
  54.  
  55. var pivot = source
  56. .GroupBy(ls => ls.OrderDate)
  57. .OrderBy(g => g.Key)
  58. .Select(g => new XElement("Date",
  59. new XAttribute("Value", g.key),
  60. g.GroupBy(ls => ls.Location)
  61. .Select(loc => new XElement("Detail",
  62. new XAttribute("Location", loc.Key),
  63. new XAttribute("Amount", loc.Sum(ls => ls.Charge))
  64. ))
  65. ));
Add Comment
Please, Sign In to add comment