首页 > 解决方案 > 如何在 SQL 中声明和使用变量

问题描述

这是我的查询 - 请帮助我了解如何在以下查询中使用变量 [标有粗体的变量]

create view cost_sheetNO (cost_No, line_No, EC, ATE, SP, E_GMValue, E_GMperc)
as  
    select 
        Vcost_sheet_line.[Cost Sheet No_], 
        Vsales_line.[Costsheet No_], 
        Vcost_sheet_line.[Landing Price],
        (select SUM(Vcost_sheet_line.[Landing Price]) 
         from Vcost_sheet_line 
         where Vsales_line.[Costsheet No_] = Vcost_sheet_line.[Cost Sheet No_]),
        Vcost_sheet_line.[List Price] * Vcost_sheet_line.[Special Vendor Discount _],
        (select declare @a decimal = sales_headerSO.OV - sales_headerSO.EC 
         from sales_headerSO), 
        (select @a - sales_headerSO.EC 
         from sales_headerSO)
    from 
        Vcost_sheet_line, Vsales_line 
    where 
        Vsales_line.[Costsheet No_] = Vcost_sheet_line.[Cost Sheet No_] 

谢谢

标签: sqlvariables

解决方案


视图没有参数,但您可以实现表格函数(您的代码看起来像 SQL Server)以根据参数获得相同的结果。

create function cost_sheetNO (@a decimal) 
returns table
return (
  select Vcost_sheet_line.[Cost Sheet No_], Vsales_line.[Costsheet No_], Vcost_sheet_line.[Landing Price], 
         (select SUM(Vcost_sheet_line.[Landing Price]) 
          from Vcost_sheet_line 
          where Vsales_line.[Costsheet No_] = Vcost_sheet_line.[Cost Sheet No_]), 
         Vcost_sheet_line.[List Price]*Vcost_sheet_line.[Special Vendor Discount _], 
         (select @a - sales_headerSO.EC from sales_headerSO)       
          from Vcost_sheet_line, Vsales_line       
          where Vsales_line.[Costsheet No_] = Vcost_sheet_line.[Cost Sheet No_] 
)

推荐阅读