简单的SQL帮助更新表

时间:2013-12-03 14:45:44

标签: sql sql-server

我有这个问题:

select orders.ID, books.Quantity from orders, Books
where customerid = '52467'
and Status = 'ready'
and orders.ID = books.OrderID

我想更新books.quantity ='1'

Update Books
SET books.Quantity = '1'

只是不确定如何编写查询。

2 个答案:

答案 0 :(得分:2)

在SQL-SERVER中,你可以这样做:

update books
set books.Quantity = '1'
from books b
inner join orders o on o.ID = b.OrderID    
where o.customerid = '52467'
  and o.status = 'ready'

答案 1 :(得分:0)

UPDATE
    Books
SET
    Books.Quantity = '1'
FROM
    Books
INNER JOIN
    Orders
ON
    Books.orderID = Orders.ID
WHERE Orders.customerid = '52467'
  and Orders.status = 'ready'

这是你需要的吗?如果您在C#等代码中使用它,则根据需要将其转换为存储过程,然后customerID和Status变为Dynamic,因为您将使用参数。

USE [Your Database Name]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[UpdateBookQuantity]
@CustomerID varchar(50),
@Status varchar(50)
AS
UPDATE
    Books
SET
    Books.Quantity = '1'
FROM
    Books
INNER JOIN
    Orders
ON
    Books.orderID = Orders.ID
WHERE Orders.customerid = @customerID
  and Orders.status = @Status
如果它是你需要经常做的事情,那就把它弹到那里。