在 SQL 服务器中声明 table 变量问题

Declare table variable issue in SQL Server

我想声明一个 table 变量,我按照 this page 中的步骤进行操作,但在 SELECT @StdRevenue; 行出现错误。看来我需要声明变量——我确实这样做了。

table Purchasing.ProductVendor:

我的代码

DECLARE @StdRevenue TABLE
(
  ProductID int, 
  Revenue money
);

--insert values to columns
INSERT INTO @StdRevenue (ProductID, Revenue)
    SELECT ProductID, StandardPrice * OnOrderQty 
    FROM Purchasing.ProductVendor
    GROUP BY ProductID;

SELECT @StdRevenue;

希望以下查询对您有所帮助....

Create table #temp

(
id int,
price varchar(5),
qty int
)

insert into #temp values(1,'50',1)

insert into #temp values(2,'500',4)

insert into #temp values(3,'100',6)



--Select All queries together

DECLARE @StdRevenue TABLE
(
  ProductID int, 
  Revenue money
);

--insert values to columns

INSERT INTO @StdRevenue (ProductID, Revenue)
    SELECT id, price * qty 
    FROM #temp


SELECT * from @StdRevenue;

----到此为止

使用

SELECT * FROM @StdRevenue;

而不是

SELECT @StdRevenue;

DECLARE @StdRevenue TABLE
(
  ProductID int, 
  Revenue money
);

--insert values to columns
INSERT INTO @StdRevenue (ProductID, Revenue)
    SELECT ProductID, StandardPrice * OnOrderQty 
    FROM Purchasing.ProductVendor
    GROUP BY ProductID;

SELECT * FROM @StdRevenue;

试试下面的代码

DECLARE @StdRevenue TABLE
(
  ProductID int, 
  Revenue money
);

--insert values to columns
INSERT INTO @StdRevenue (ProductID, Revenue)
    SELECT 1, 2

SELECT * from @StdRevenue;

这里你错过了在 table 名字前写 * from 比如 @StdRevenue