2014-09-24 128 views
0

我写了两条SQL语句,因为我无法弄清楚如何解决我的问题。将两个SQL语句合并为一个

一个叫做get_ID,另一个叫Save Record。我希望保存记录能够读取并查看是否在vb前端的某个字段中输入了我的id,并且如果没有它为其分配一个,但我无法弄清楚这是我目前为止的情况。它的工作原理,但我知道应该有更好的方法来做到这一点。帮助这个问题会很好

ALTER PROCEDURE [dbo].[Product_GetID] 
AS 
BEGIN 
    DECLARE @NewProductID as int 

    /* Get New Record */ 
    SET @NewProductID = (SELECT ISNULL(MAX(ProductID) + 1, 1) FROM Product) 

    SELECT 
     ISNULL(MAX(ProductID) + 1, 1) AS NewIDNo 
    FROM Product 

    INSERT INTO Product (ProductID, CategoryID, Description, Price) 
    VALUES (@NewProductID, 0, '', 0) 
END 

ALTER PROCEDURE [dbo].[Product_SaveRecord] 
    @ProductID as int, 
    @CategoryID as tinyint, 
    @Description as varchar(80), 
    @FullDescription as varchar(240), 
    @Price as decimal(8, 2), 
    @MarkupPer as decimal(8, 2), 
    @LabourHours as decimal(8, 2), 
    @LabourRate as decimal(8, 2), 
    @Stock as integer 
AS 
BEGIN 
    /* Update Record */ 
    UPDATE Product 
    SET CategoryID = @CategoryID, 
     Description = @Description, 
     FullDescription = @FullDescription, 
     Price = @Price, 
     MarkupPer = @MarkupPer, 
     LabourHours = @LabourHours, 
     LabourRate = @LabourRate, 
     Stock = @Stock 
    WHERE ProductID = @ProductID 
END 
+0

不清楚你在问什么,但是你看看[MERGE T-SQL](http://msdn.microsoft.com/en-us/library/bb510625.aspx)语句吗? – Steve 2014-09-24 15:42:55

+1

你的问题有点不清楚。你说过你无法弄清楚,但也说明你的代码有效。如果你的代码可以工作,但你只是想让它变得更好,你的问题可能更适合[代码评论](http://codereview.stackexchange.com/)。 – skrrgwasme 2014-09-24 15:43:08

+0

是的,我知道这可能是一个问题,这是有很多用户在系统上,因为我认为coulod发生的是,它可以重叠,因为它必须回去和前进,完成保存记录的一项任务 – Richard 2014-09-24 15:47:58

回答

0

下面我对你的代码做了一些修改。我相信有更多,但这将有助于:

ALTER PROCEDURE [dbo].[Product_SaveRecord] 
    @ProductID as int, 
    @CategoryID as tinyint, 
    @Description as varchar(80), 
    @FullDescription as varchar(240), 
    @Price as decimal(8, 2), 
    @MarkupPer as decimal(8, 2), 
    @LabourHours as decimal(8, 2), 
    @LabourRate as decimal(8, 2), 
    @Stock as integer 
AS 
BEGIN 
    IF @ProductID IS NULL BEGIN 
     SET @ProductID = (SELECT ISNULL(MAX(ProductID) + 1, 1) FROM Product) 

     INSERT INTO Product (ProductID, CategoryID, Description, Price) --Add the rest of the columns 
     VALUES (@NewId, @CategoryID, @Description, @Price) --Add the rest of the columns 
    END ELSE BEGIN 
     /* Update Record */ 
     UPDATE Product 
     SET CategoryID = @CategoryID, 
      Description = @Description, 
      FullDescription = @FullDescription, 
      Price = @Price, 
      MarkupPer = @MarkupPer, 
      LabourHours = @LabourHours, 
      LabourRate = @LabourRate, 
      Stock = @Stock 
     WHERE ProductID = @ProductID 
    END 
END 

随着你越来越舒服,你也可以使用MERGE方法,它非常相似。