SQL查询存储过程

时间:2015-07-23 02:31:07

标签: sql-server

创建一个传递SalesOrderID作为参数的存储过程。 此存储过程将返回SalesOrderID,交易日期,发货日期,城市和州。它没有运行

答:

Create PROCEDURE proc_findProductInfo
    @SalesOrderID int,
    @SalesOrderOut int OUTPUT,
    @OrderDate datetime OUTPUT,
    @ShipDate datetime OUTPUT,
    @CityState varchar(100) OUTPUT
AS
BEGIN
    SET NOCOUNT ON; 
    SET @SalesOrderOut = @SalesOrderID
    SET @OrderDate = (SELECT OrderDate FROM SALES.SalesOrderHeader )
    SET @ShipDate = (SELECT ShipDate FROM Sales.SalesOrderHeader)
    SET @CityState = (SELECT a.City, st.Name
                      FROM Sales.SalesOrderHeader s  
                      INNER JOIN Person.Address a ON                s.ShipToAddressID = a.AddressID
                      INNER JOIN Person.StateProvince st ON s.TerritoryID = st.TerritoryID
                      WHERE SalesOrderID = @SalesOrderID)
END

DECLARE @OrderNum int, @Date datetime, @qty1 int, @Date1 datetime

EXEC proc_findProductInfo 63936, 
                     @SalesOrderOut = @OrderNum OUTPUT,
                     @OrderDate = @Date OUTPUT,
                     @ShipDate = @date1,
                     @CityState = @qty1 output

SELECT @OrderNum, @date, @qty1, @Date1

错误讯息:

  

Msg 116,Level 16,State 1,Procedure proc_findProductInfo,Line 25
  当选择列表中只能指定一个表达式时   子查询不是用EXISTS引入的

2 个答案:

答案 0 :(得分:1)

你使这种方式比以前更难:

Create PROCEDURE proc_findProductInfo
    @SalesOrderID int
AS
BEGIN
    SET NOCOUNT ON; 

    SELECT  s.SalesOrderID, s.OrderDate, s.ShipDate, a.City,st.Name
    FROM    Sales.SalesOrderHeader s     
    INNER JOIN Person.Address a ON s.ShipToAddressID = a.AddressID
    INNER JOIN Person.StateProvince st ON s.TerritoryID=st.TerritoryID
    WHERE s.SalesOrderID = @SalesOrderID
END

我甚至不确定你在这里需要StateProvince表...这个问题可能让你信任地址记录。

答案 1 :(得分:0)

抱怨以下

SET @CityState = (
    SELECT          a.City,st.Name

您正在选择城市和州名称并尝试将其分配给变量。 您需要将它们连接或合并为单个输出,或者使用以下类型的select将每个类型分配给变量。

select 
    @var1 = field1,
    @var2 = field2,
...

如下所示

SET @SalesOrderOut = @SalesOrderID

SELECT         @OrderDate = s.OrderDate,
               @ShipDate = s.ShipDate,
               @CityState = CONCAT(a.City, ", ", st.Name)
FROM            Sales.SalesOrderHeader s     
inner JOIN Person.Address a
ON              s.ShipToAddressID = a.AddressID
inner JOIN Person.StateProvince st
on s.TerritoryID=st.TerritoryID
WHERE SalesOrderID = @SalesOrderID