使用声明和设置变量创建存储过程

时间:2012-02-11 12:43:31

标签: sql-server sql-server-ce

我正在创建一个存储过程,其中只有值必须通过,我必须从多个表中检索多个值。我尝试这样做,但它显示错误,如

  

开始附近的语法不正确

  

必须声明标量变量@OrderID

Declare @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT

SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)

SET @AppointmentID = (SELECT  AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)

SET @PurchaseOrderID = (SELECT  PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)

2 个答案:

答案 0 :(得分:18)

您应该尝试使用此语法 - 假设您希望将@OrderID作为参数用于存储过程:

CREATE PROCEDURE dbo.YourStoredProcNameHere
   @OrderID INT
AS
BEGIN
 DECLARE @OrderItemID AS INT
 DECLARE @AppointmentID AS INT
 DECLARE @PurchaseOrderID AS INT
 DECLARE @PurchaseOrderItemID AS INT
 DECLARE @SalesOrderID AS INT
 DECLARE @SalesOrderItemID AS INT

 SELECT @OrderItemID = OrderItemID 
 FROM [OrderItem] 
 WHERE OrderID = @OrderID

 SELECT @AppointmentID = AppoinmentID 
 FROM [Appointment] 
 WHERE OrderID = @OrderID

 SELECT @PurchaseOrderID = PurchaseOrderID 
 FROM [PurchaseOrder] 
 WHERE OrderID = @OrderID

END

当然,只有在您返回一个值(不是多个值!)时才有效。

答案 1 :(得分:7)

我假设您要传递订单ID。所以:

CREATE PROCEDURE [dbo].[Procedure_Name]
(
    @OrderID INT
) AS
BEGIN
    Declare @OrderItemID AS INT
    DECLARE @AppointmentID AS INT
    DECLARE @PurchaseOrderID AS INT
    DECLARE @PurchaseOrderItemID AS INT
    DECLARE @SalesOrderID AS INT
    DECLARE @SalesOrderItemID AS INT

    SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
    SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
    SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END