Search code examples
sqlsql-serverinline-functions

Inline SQL function which sometimes must update database


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.


Solution

  • 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