问题
I have a SQL Server stored procedure that I want to use to create a report in my application (c#).
Because the table in the procedure is dynamically created I am having trouble using it to create a report.
How can I use this procedure to create a report in my application?
I am using VS2010, SQL Server 2008 R2
I created a dataset in VS but not sure how to use it from there. The report wizard cannot use the dataset I created.
I gave thought to somehow using this to create a view and then generate a dataset from that but could not figure that out.
I hope I have provided enough info for someone to give me some direction.
PROCEDURE sp_RD_Reporting_View_ExportedData_For_Period
(
@StartDate date,
@EndDate date
)
AS
CREATE TABLE #tmp
(
StartDate DATETIME,
EndDate DATETIME,
FomatedDate VARCHAR(20)
)
--Calculate the date ranges
;WITH Nbrs ( n ) AS (
SELECT 0 UNION ALL
SELECT 1+n FROM Nbrs WHERE n < 6 )
INSERT INTO #tmp
SELECT
DATEADD(DAY,-n,@StartDate),
DATEADD(DAY,-n,@EndDate),
convert(varchar, DATEADD(DAY,-n,@EndDate), 110)
FROM
Nbrs
ORDER BY
-n
--The date columns for the pivot
DECLARE @cols VARCHAR(MAX)
SELECT @cols = COALESCE(@cols + ','+QUOTENAME(FomatedDate),
QUOTENAME(FomatedDate))
FROM
#tmp
--Declaring some dynamic sql and executing it
DECLARE @query NVARCHAR(4000)=
N'SELECT
*
FROM
(
SELECT ExportData.EmployeeID AS EmpID,
ABRAempInfo.EmpFullName AS Name,
ExportData.PayType AS PayType,
tmp.FomatedDate,
SUM(ExportData.Quantity) AS Hours
FROM ExportData
JOIN ABRAempInfo
ON ExportData.EmployeeID = ABRAempInfo.EmpID
JOIN #tmp AS tmp
ON ExportData.ChargeDate = tmp.FomatedDate
WHERE ChargeDate BETWEEN tmp.StartDate AND tmp.EndDate
GROUP BY ExportData.EmployeeID, ExportData.PayType, tmp.FomatedDate, ABRAempInfo.EmpFullName
) AS p
PIVOT
(
SUM(Hours)
FOR FomatedDate IN ('+@cols+')
) AS pvt'
EXECUTE(@query)
DROP TABLE #tmp
回答1:
I have run into something that I think is similar - trying to get Linq to Sql to build me a result set from a stored proc that uses Dynamic SQL to select results. Here is how I solved my issue... it is very much a work around, but you won't really be able to get a wizard to work off a dynamic result set. Also note, that if your dynamic sql returns differing columns, it is not likely to work.
- Run your dynamic statement and output only the SQL statement (print the statement, don't execute it)
- Modify your stored procedure to return output via the sql statement you got from #1
- You now have a standard stored procedure - use this to build your report from.
- After your report is tested and working ok, Modify your stored procedure again and plug the dynamic sql back in.
来源:https://stackoverflow.com/questions/13464503/using-a-stored-procedure-containing-dynamic-sql-to-create-a-report-in-c-sharp-r