2014-09-03 42 views
0

嵌入式SQL函数是否有可能创建一个函数/过程,它可以在一个SQL语句中使用这样的:有时必须更新数据库

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

LookupOrCreateProduct应该寻找一个产品表通过串(条形码)和:
*如果条形码被发现 - 收益产品ID
*如果找不到条形码 - 创建Products表与新的条形码的新纪录,并返回其ID

我探索的SQL Server函数,但它们不允许INSERT或函数体内的任何其他数据库修改。存储过程可以返回值,但它们只能是int类型。我的ID栏是bigint。另一个选择是使用输出参数,但是我不清楚,我怎样才能将它内联到SQL语句中。谢谢。

+0

设置输出参数,并从存储过程返回,并将其保存到变量,然后用它为您的插入查询... – 2014-09-03 15:49:28

+0

你不能这样做的功能。 [你应该使用OUTPUT参数,而不是RETURN值](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/09/bad-habits-to-kick-using-select-or-return -instead-的-output.aspx)。返回值用于错误/状态代码,不适用于数据;其中一个主要原因正是你发现的:它们只对整数有用。 – 2014-09-03 16:25:08

回答

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 
+0

为什么'IF EXISTS'检查?即使BarCode被索引,这也是浪费额外的检查。 'SELECT @ProductID ='...'IF @ProductID IS NULL'然后插入。 – 2014-09-03 16:27:39

+0

@AaronBertrand当然,这样做更有意义,谢谢你的指针:) – 2014-09-03 16:50:42

1

我认为你能做的最好的是在存储过程中的输出参数:Bigint数据类型的

declare @product_id int; 

begin transaction; 

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

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

commit transaction; 
相关问题