1

I'd like to ask help on this small query of mine. Im doing a query and a sub query on my sub query i want to have it parameterized. Is there a way to do it? Please see my query script.

select sum(issue) as [Issue], sum(nonissue) as [NonIssue]
from
(
AS
    select
        case when isissue = 1 then 1 else 0 end as 'issue',
        case when isissue = 0 then 1 else 0 end as 'nonissue',
        LastTicketStatusID
    from
        vw_Tickets
    where
        LastTicketStatusID = @LastTicketStatusID
) 
as Tickets

I always got an error Must declare the table variable "@LastTicketStatusID". where should i declare the parameter?

Thanks, Nhoyti

3
  • 1
    Please clarify - do you want @LastTicketStatusID to come from the outer query or from the code that is executing your command batch? Commented Jul 8, 2009 at 16:12
  • What's the AS after the open parenthesis after the first FROM? Commented Jul 8, 2009 at 16:35
  • I'm interested to know if there's an answer how to do this with a value from the outer query, one of the possibilities @Christian posed. Commented Dec 13, 2010 at 18:50

3 Answers 3

2

If this is for a stored procedure...

CREATE PROCEDURE [dbo].[ProcedureName]
    @LastTicketStatusID INT
AS 

select
sum(issue) as [Issue], 
sum(nonissue) as [NonIssue]
from (
    select
    case when isissue = 1
        then 1 else 0 end as 'issue',
    case when isissue = 0
        then 1 else 0 end as 'nonissue',
    LastTicketStatusID
from vw_Tickets 
where LastTicketStatusID = @LastTicketStatusID ) as Tickets

Otherwise

DECLARE @LastTicketStatusID INT
SELECT @LastTicketStatusID = yourDesiredID
Sign up to request clarification or add additional context in comments.

Comments

1

Not pertinant to your question, but assuming that vw_Tickets.isissue is a bit field (or otherwise constrained to values of zero or one.) the inline query can be removed to simplify Launchy's answer:

select sum(isissue) as [Issue], 
    sum(1 - isissue) as [NonIssue]
from vw_Tickets 
where LastTicketStatusID = @LastTicketStatusID

1 Comment

exactly; I'm not a fan of unnecessary subqueries
0

at the very top of the query

Declare @LastTicketStatusID int
set @lastTicketStatusID = ####

Comments

Your Answer

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