SQL Server 2008,将列作为输出参数返回

时间:2011-08-19 09:07:22

标签: sql-server

我有以下存储过程

ALTER PROCEDURE [dbo].[sp_web_orders_insert]
(
    @userId int = default,
    @custId int = default,
    @orderDate datetime = default,
    @orderTotal money = default,
    @statusId int = default,
    @orderReference varchar(50) = default,
    @custReference varchar(50) = default,
    @order_ID INT output,
    @orderReferenceOutput varchar(50) output
)
AS
    SET NOCOUNT OFF;

    INSERT INTO [web_orders] ([user_ID], [cust_ID], [orderDate], [orderTotal], [statusId], [orderReference], [custReference]) 
    VALUES (@userId, @custId, @orderDate, @orderTotal, @statusId , 'PLC' + REPLICATE('0', (7 - LEN((select MAX(order_ID) from web_orders)))) +  CAST((select(max(order_ID)+1) from web_orders) AS VARCHAR(5)), @custReference);

    SET @order_ID = @@IDENTITY

    SET @orderReferenceOutput = select top 1 orderReference from web_orders

但是在select附近遇到语法问题,如何找回刚刚插入的orderReference的值?

3 个答案:

答案 0 :(得分:3)

两点:

  • 使用SCOPE_IDENTITY()代替@@IDENTITY(请参阅why this is here或Google for it ...)
  • 使用SELECT语句获取您的价值

类似的东西:

SET @order_ID = SCOPE_IDENTITY()

SELECT 
    @orderReferenceOutput = SELECT orderReference  
                            FROM dbo.web_orders
                            WHERE order_Id = @order_ID

答案 1 :(得分:0)

尝试以下代码部分,希望它能为您提供帮助

SET @orderReferenceOutput = select @orderReference=(top 1 orderReference) from web_orders

答案 2 :(得分:0)

select @order_ID = order_ID, @orderReferenceOutput = orderReference  
  from dbo.web_orders
  where order_ID = SCOPED_IDENTITIY();

或者直接删除输出参数并返回插入的记录:

select * from dbo.web_orders where order_Id = SCOPED_IDENTITIY();

是。程序可以返回数据,就像查询一样。