带参数的子查询?

时间:2009-07-08 15:58:50

标签: sql parameters subquery

我想在我的这个小问题上寻求帮助。我在我的子查询上进行查询和子查询,我想让它参数化。有办法吗? 请参阅我的查询脚本。

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

我总是遇到错误必须声明表变量“@LastTicketStatusID”。我应该在哪里声明参数?

谢谢, Nhoyti

3 个答案:

答案 0 :(得分:2)

如果这是用于存储过程......

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

否则

DECLARE @LastTicketStatusID INT
SELECT @LastTicketStatusID = yourDesiredID

答案 1 :(得分:1)

与您的问题不相关,但假设vw_Tickets.isissue是一个位字段(或以其他方式约束为零或一个值)。可以删除内联查询以简化Launchy的答案:

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

答案 2 :(得分:0)

位于查询的最顶层

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