1

首先,如果找到代理名称,我必须从查询表中找到代理名称,然后如果未找到代理名称,则如果部分将 wrk n,则第二个查询 dat 是其他部分将起作用。以下是我的查询,请让我知道我哪里错了。提前致谢

create proc ConfirmationMail_ToAgent
(
    @Enquiry_Id nvarchar(50)
)
as
begin
    select Agent_Name from Enquiry where Enquiry_Id = @Enquiry_Id as jh
    if(jh != 'Select')
    begin
        select e.Agent_Name,e.Agent_Email,e.Client_Name,e.Handled_By,ef.EMail_Id from Enquiry e inner join Employee_FullDetail ef on e.Handled_By = ef.First_Name where e.Enquiry_Id = @Enquiry_Id
    end
    else
    begin
       select e.Client_Name,e.Client_Address,e.Handled_By,ef.EMail_Id from Enquiry e inner join Employee_FullDetail ef on e.Handled_By = ef.First_Name where e.Enquiry_Id = @Enquiry_Id
    end
end
4

2 回答 2

0

SQL Server中,您使用以下语法将列分配给变量

DECLARE @Var varchar(xx)
SELECT @Var = [ColName] FROM [TableName]

因此,您的查询应如下所示:

create proc ConfirmationMail_ToAgent
(
@Enquiry_Id nvarchar(50)
)
as
BEGIN
    DECLARE @jh VARCHAR(100)
    select @jh= Agent_Name from Enquiry where Enquiry_Id = @Enquiry_Id 
    if(@jh != 'Select')
    begin
        select e.Agent_Name,e.Agent_Email,e.Client_Name,e.Handled_By,ef.EMail_Id from Enquiry e inner join Employee_FullDetail ef on e.Handled_By = ef.First_Name where e.Enquiry_Id = @Enquiry_Id
    end
    else
    begin
        select e.Client_Name,e.Client_Address,e.Handled_By,ef.EMail_Id from Enquiry e inner join Employee_FullDetail ef on e.Handled_By = ef.First_Name where e.Enquiry_Id = @Enquiry_Id
    end
end
于 2013-09-21T11:53:05.937 回答
0

好吧,我真的认为您必须阅读编程中的 DRY 原则。请遵循此原则,它将帮助您将来维护您的代码。看起来您在这里不需要 2 个查询,您可以只使用一个:

create proc ConfirmationMail_ToAgent
(
     @Enquiry_Id nvarchar(50)
)
as
begin
    select
        case when e.Agent_Name != 'Select' then e.Agent_Name else e.Client_Name end as Name,
        case when e.Agent_Name != 'Select' then e.Agent_Email else e.Client_Address end as Address,
        e.Handled_By, ef.EMail_Id
    from Enquiry as e
        inner join Employee_FullDetail as ef on ef.First_Name = e.Handled_By
    where e.Enquiry_Id = @Enquiry_Id
end

这将更容易维护- 如果您必须向结果集中添加列,您只需执行一次,更易于阅读- 您不必考虑 - 这两个查询有什么区别?为了完全遵循 DRY 原则,可以重写此查询,例如,如下所示:

create proc ConfirmationMail_ToAgent
(
     @Enquiry_Id nvarchar(50)
)
as
begin
    select
        C.Name, C.Email,
        e.Client_Name, e.Handled_By, ef.EMail_Id
    from Enquiry as e
        inner join Employee_FullDetail as ef on ef.First_Name = e.Handled_By
        outer apply ( 
            select e.Agent_Name, e.Agent_Email where e.Agent_Name != 'Select' union all
            select e.Client_Name, e.Client_Address where e.Agent_Name == 'Select'
        ) as C(Name, Email)
    where e.Enquiry_Id = @Enquiry_Id
end
于 2013-09-21T15:19:26.820 回答