[英]Pass a table variable to stored procedure?
I have this table我有这张桌子
CREATE TABLE [dbo].[Sale]
(
[SaleId] [int] IDENTITY(1,1) PRIMARY KEY,
[SaleDate] [datetime] NOT NULL DEFAULT GETDATE(),
[UserPhone] char(10) NOT NULL,
[NumberSale] [int] NOT NULL,
)
Then I have this table variable然后我有这个表变量
DECLARE @sale1 TABLE
(
Phone char(10),
GoodId int,
GoodCount int
)
INSERT INTO @sale1
VALUES ('0671112221', 1, 2),
('0671112221', 4, 1),
('0671112221', 13, 2);
I am creating a stored procedure to input data into the table using table variable.我正在创建一个存储过程以使用表变量将数据输入表中。 But table is underlined.
但是表格有下划线。
CREATE PROCEDURE spSalesAndSalesPosInsert
@data table -- here is a mistake
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION;
INSERT INTO Sale (UserPhone, NumberSale)
SELECT Phone, GoodCount
FROM @data
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
END CATCH;
END;
What am I doing wrong?我究竟做错了什么?
The table
keyword is reserved for other scenarios than passing a parameter. table
关键字保留用于传递参数以外的其他场景。
Have look a this example from the documentation that passes a table-valued parameter to a stored procedure by creating a user-defined type .从文档中查看此示例,该示例通过创建用户定义类型将表值参数传递给存储过程。
You need to declare a user-defined type for the table.您需要为该表声明一个用户定义的类型。
CREATE TYPE myTableType AS TABLE
(
Phone char(10), GoodId int, GoodCount int
)
Then you can use it:然后你可以使用它:
declare @sale1 myTableType
insert into @sale1
values
('0671112221', 1, 2),
('0671112221', 4, 1),
('0671112221', 13, 2);
create proc spSalesAndSalesPosInsert
@data myTableType
as
begin
--Etc....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.