SQL Server:从查询输出设置变量

时间:2010-10-22 17:37:10

标签: sql sql-server sql-server-2005

嘿所有,我想知道如何将变量设置为以下查询字符串的输出:

SELECT count(*) fees_quantity,
   1.5 fees_price,
   1.5 * count(*) fees_amount,
   round(SUM((CONVERT(int,Points) * .1)),0)) redep_amount,
   round(SUM((CONVERT(int,Points) * .1)),0)) + 1.5 * count(*) total_amount
FROM tblHGP HGP,  
   OrderDetails OD, 
   tblInvoices i
  JOIN tblCS cs ON i.INumber = cs.INumber
  JOIN tblECI ac ON i.INumber = ac.INumber 
WHERE cs.SoldTo = HGP.ECard 
AND issued BETWEEN '2010-09-01' AND '2010-09-30 23:59:59' 
AND Country = 'US' 
AND HGP.iNumber = OD.orderdetail

我该怎么办?

DECLARE @FeesQty varchar(3)
DECLARE @FeesTotal varchar(10)
DECLARE @RedepTotal varchar(10)
DECLARE @Total varchar(10)

@FeesQty = fees_quantity
@FeesTotal = fees_amount
@RedepTotal = redep_amount
@Total = total_amount

怎么办呢?

谢谢!

大卫

1 个答案:

答案 0 :(得分:4)

像这样:

DECLARE @FeesQty varchar(3)
DECLARE @FeesTotal varchar(10)
DECLARE @RedepTotal varchar(10)
DECLARE @Total varchar(10)

SELECT
    @FeesQty = count(*),
    @FeesTotal = 1.5 * count(*),
    @RedepTotal = round(SUM((CONVERT(int,Points) * .1)),0)),
    @Total = round(SUM((CONVERT(int,Points) * .1)),0)) + 1.5 * count(*)
FROM tblHGP HGP,  
   OrderDetails OD, 
   tblInvoices i
  JOIN tblCS cs ON i.INumber = cs.INumber
  JOIN tblECI ac ON i.INumber = ac.INumber 
WHERE cs.SoldTo = HGP.ECard 
AND issued BETWEEN '2010-09-01' AND '2010-09-30 23:59:59' 
AND Country = 'US' 
AND HGP.iNumber = OD.orderdetail

或者 - 我想 - 如果你不想修改你的查询:

DECLARE @FeesQty varchar(3)
DECLARE @FeesTotal varchar(10)
DECLARE @RedepTotal varchar(10)
DECLARE @Total varchar(10)

SELECT
    @FeesQty = t.fees_quantity,
    @FeesTotal = t.fees_amount,
    @RedepTotal = t.redep_amount,
    @Total = t.total_amount
FROM (
    SELECT count(*) fees_quantity,
       1.5 fees_price,
       1.5 * count(*) fees_amount,
       round(SUM((CONVERT(int,Points) * .1)),0)) redep_amount,
       round(SUM((CONVERT(int,Points) * .1)),0)) + 1.5 * count(*) total_amount
    FROM tblHGP HGP,  
       OrderDetails OD, 
       tblInvoices i
      JOIN tblCS cs ON i.INumber = cs.INumber
      JOIN tblECI ac ON i.INumber = ac.INumber 
    WHERE cs.SoldTo = HGP.ECard 
    AND issued BETWEEN '2010-09-01' AND '2010-09-30 23:59:59' 
    AND Country = 'US' 
    AND HGP.iNumber = OD.orderdetail
) t