如何在@body中为SQL Server声明变量?

时间:2019-01-21 15:51:55

标签: sql sql-server email variables html-email

我正在尝试通过SQL Server发送电子邮件。一切正常,但是我无法让@body接受我声明的变量。

我也尝试调用一个新变量并将其设置为@body,但是我遇到了同样的问题。

Declare @Body varchar(max),    
      @TableHead varchar(max),
      @TableTail varchar(max),
      @message as varchar(max)     

Set @message=
    (

    DECLARE @CNT as int, @SLS as NVARCHAR(10)
    select  [employeeid], [Sales]
    into #loctempemployee from tblEmployees  

    Set @CNT =  (Select COUNT (Distinct EmployeeID) from #loctempemployee)

    SELECT tr.Principal As [TD], tr.[Company Name] As [TD], ai.[Action Item] As [TD], ai.Owners As [TD], ai.[Due Date] As [TD], ai.Updated As [TD]
    FROM [tblActionItem] ai
    INNER JOIN tblTripReport tr ON ai.TripReportID = tr.tripreportID
    INNER JOIN tblCustomers cu ON cu.CustomerID = tr.[Customer ID]
    INNER JOIN tblEmployees em ON em.EmployeeID = cu.EmployeeID
    WHERE em.Sales = (Select sales from #loctempemployee Where EmployeeID = (Select top 1 EmployeeID from #loctempemployee))
    For XML raw('tr'), Elements

    Delete #loctempemployee Where EmployeeID = (Select top 1 EmployeeID from #loctempemployee) 
    set @CNT = @CNT -1;

    End

    drop table #loctempemployee 
)

Select @Body = (@message)

2 个答案:

答案 0 :(得分:0)

注释非常正确-您无法在将变量分配给单个数据类型的情况下执行大量的SQL。

如果将所需的数据放入#temp表中,则可以使用以下内容。

 function() {
    var h2Element = document.getElementsByTagName('h2')[1];
    var innerText = h2Element.innerText;
    console.log('The text you need is: ' + innerText);
    return innerText;
  }

答案 1 :(得分:0)

如果我对您的理解正确,则您正在尝试将SELECT的结果分配给@message。您使用的语法不正确。您无法像TSQL那样在SET中运行一批语句。只要查询产生字符串结果,就可以分配@message的查询结果。因此,我认为您可能希望将代码更改为类似的内容(将其他语句从SET语句中拉出)。

Declare @Body varchar(max),    
      @TableHead varchar(max),
      @TableTail varchar(max),
      @message as varchar(max);     


    DECLARE @CNT as int, @SLS as NVARCHAR(10);
    select  [employeeid], [Sales]
    into #loctempemployee from tblEmployees;  

    Set @CNT =  (Select COUNT (Distinct EmployeeID) from #loctempemployee);

Set @message=
    (
    SELECT tr.Principal As [TD], tr.[Company Name] As [TD], ai.[Action Item] As [TD], ai.Owners As [TD], ai.[Due Date] As [TD], ai.Updated As [TD]
    FROM [tblActionItem] ai
    INNER JOIN tblTripReport tr ON ai.TripReportID = tr.tripreportID
    INNER JOIN tblCustomers cu ON cu.CustomerID = tr.[Customer ID]
    INNER JOIN tblEmployees em ON em.EmployeeID = cu.EmployeeID
    WHERE em.Sales = (Select sales from #loctempemployee Where EmployeeID = (Select top 1 EmployeeID from #loctempemployee))
    For XML raw('tr'), Elements
    );


Delete #loctempemployee Where EmployeeID = (Select top 1 EmployeeID from #loctempemployee); 
    set @CNT = @CNT -1;

drop table #loctempemployee; 

Select @Body = (@message);

此外,您是否正在以未显示的循环进行此操作?有一个END没有相应的BEGIN,这也可以解释行set @CNT = @CNT -1;