将两个SQL语句合并为一个

时间:2014-09-24 15:36:22

标签: sql sql-server vb.net

我写了两个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

1 个答案:

答案 0 :(得分: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方法,它非常相似。