I am working on this stored proc which is suppose to give values based on the input Quarter and year.
The stored proc has dynamic 2 columns which has the Sum of Amounts. But in place of the column name its showing No column name for those 2 columns (S1, P1) and even not giving the values.
create proc [dbo].[Summary]
@Quarter int,
@Year int
AS
BEGIN
Declare @SC AS decimal(18,0)
Declare @PO AS decimal(18,0)
Declare @INV AS decimal(18,0)
SELECT BD.id,
BD.project,
status,
(SELECT Sum(amount) AS S1
FROM details a
WHERE status = 'S1'
AND BD.project = a.project),
(SELECT Sum(amount) AS P1
FROM details b
WHERE status = 'P1'
AND BD.project = b.project)
FROM projectdetails (nolock) BD
INNER JOIN details (nolock) D
ON BD.project = D.project
WHERE BD.quarter = @Quarter
AND BD.year = @Year
AND BD.project = D.project
GROUP BY BD.lineid,
BD.project,
status
END
When you use a function in a column list, the original column name is not retained. You need to use a column alias. For example:
SELECT BD.ID,
BD.Project,
Status,
(SELECT Sum(amount) AS S1
FROM details a
WHERE status = 'S1'
AND BD.project = a.project) AS SumS1, --Added alias here
(SELECT Sum(amount) AS P1
FROM details b
WHERE status = 'P1'
AND BD.project = b.project) AS SumP1 --And here
FROM ...
As to why you are not getting data, that is because your query is not returning any data. Try running those select statements separately to see where the problem is.
You need to give them alias outside the Subquery
create proc [dbo].[Summary]
@Quarter int,
@Year int
AS
BEGIN
Declare @SC AS decimal(18,0)
Declare @PO AS decimal(18,0)
Declare @INV AS decimal(18,0)
SELECT BD.ID,
BD.Project,
Status,
(Select SUM(Amount) from Details a where Status='S1' and BD.Project = a.Project) as S1,
(Select SUM(Amount) from Details b where Status='P1' and BD.Project = b.Project) as P1
FROM ProjectDetails (NOLOCK) BD
inner join Details (NOLOCK) D on BD.Project = D.Project
WHERE BD.Quarter = @Quarter and BD.Year = @Year and BD.Project = D.Project
Group By BD.LineID, BD.Project,Status
END
Use alias
name to those two sub-queries to get column names in result. It can be rewritten like this
SELECT BD.id,
BD.project,
status,
Sum(case when status = 'S1' then amount else 0 end) AS S1,
Sum(case when status = 'P1' then amount else 0 end) AS P1
FROM projectdetails BD
INNER JOIN details D
ON BD.project = D.project
WHERE BD.quarter = @Quarter
AND BD.year = @Year
AND BD.project = D.project
GROUP BY BD.lineid,
BD.project,
status
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.