0

Is it possible to create a function/procedure, which could be used in a SQL statement like this:

INSERT INTO Journal(ProductID,Quantity) VALUES(LookupOrCreateProduct('12345678'),5)

LookupOrCreateProduct should look up a product table by string (barcode) and:
* If barcode is found - return Product ID
* If barcode is not found - create a new record in Products table with new barcode and return its ID

I explored SQL Server functions, but they do not allow INSERTs or any other database modification inside function body. Stored procedures can return values, but they can only be of int type. My ID column is bigint. Another option is to use output parameter but then it is not clear to me, how can I inline it in SQL statement. Thank you.

4

2 回答 2

2
CREATE PROCEDURE LookupOrCreateProduct 
   @BarCode    VARCHAR(100),
   @ProductID  BIGINT OUTPUT
AS
BEGIN
   SET NOCOUNT ON;


       SELECT TOP 1 @ProductID = ProductID
       FROM dbo.Products 
       WHERE BarCode = @BarCode

   IF(@ProductID IS NULL)
    BEGIN
      INSERT INTO dbo.Products(Barcode)
      VALUES (@BarCode)

      SET @ProductID = SCOPE_IDENTITY();
    END   

END
于 2014-09-03T15:55:07.753 回答
1

我认为您能做的最好的事情是存储过程中的输出参数:

declare @product_id int;

begin transaction;

exec dbo.LookupOrCreateProduct '12345678', @product_id out;

insert into journal (productId, quantity) values (@product_id, 5);

commit transaction;
于 2014-09-03T15:49:43.333 回答