我在这项任务的最后一部分,任何帮助都会非常感谢你!
exec DeleteRecordWithUserInputCompanyName 'Costco'
它会说Command(s)已成功完成,但行未被删除。
任务存储过程,允许在给定公司名称作为输入的情况下删除客户。不要留下任何“孤儿”记录!
我的代码
Create Procedure DeleteRecordWithUserInputCompanyName @CompanyName varchar(50)as
--Get All Company names
Declare @@CompanyNames varchar(50)
select @@CompanyNames = Company from Customers
--Get CustomerNumber mathing the company name
Declare @@CustomerNumber char(4)
select @@CustomerNumber = CustomerNo from Customers where Company = @CompanyName
--Get Order Number mathing Customer Number
Declare @@OrderNumber int
select @@OrderNumber = OrderNo from Orders where CustomerNo = @@CustomerNumber
if (@@CompanyNames = @CompanyName)
Begin
ALTER TABLE Customers NOCHECK CONSTRAINT ALL
Delete from Customers where Company = @CompanyName
ALTER TABLE Customers CHECK CONSTRAINT ALL
Delete from Orders where CustomerNo = @@CustomerNumber
ALTER TABLE SalesDetail NOCHECK CONSTRAINT ALL
Delete from SalesDetail where OrderNo = @@OrderNumber
ALTER TABLE SalesDetail CHECK CONSTRAINT ALL
End
表
Create Table Customers
(
CustomerNo char(4)
Constraint ck_CustomerNoHas4positionsWithNumbers
Check(CustomerNo like'[0-9],[0-9],[0-9],[0-9]'),
Company varchar(50) not null,
CustomerRep char(3),
CreditLimt money default(20000.00),
PRIMARY KEY(CustomerNo)
)
Create Table Orders
(
OrderNo int,
OrderDate Date not null,
CustomerNo char(4) not null,
SalesRep char(3) not null
PRIMARY KEY(OrderNo)
)
Create Table SalesDetail
(
SaleDetailID int,
ManufactureID char(3) Constraint ck_ManufactureIDFromSaleDetails check(ManufactureID like'[a-z],[a-z],[a-z]') not null,
ProductID char(5) Constraint ck_ProductIDSalesDetail check(ProductID like'[0-9],[0-9],[a-z],[a-z],[a-z]') not null,
OrderNo int,
qtyOrdered int
PRIMARY KEY(SaleDetailID)
)
答案 0 :(得分:3)
select @@CompanyNames = Company from Customers
在此查询之后@@CompanyNames
将最后一个公司保留在表客户中,因为if条件返回false,因此内部块不会被执行
试试这个
Create Procedure DeleteRecordWithUserInputCompanyName @CompanyName varchar(50)as
Begin
--Delete Sale Detail First
Delete from SalesDetail where orderno in (select OrderNo from Orders where
CustomerNo in (select CustomerNo from Customer where Company=@CompanyName))
--Delete From Orders Table
Delete from Orders where CustomerNo in (select CustomerNo from Customer where Company=@CompanyName)
--Delete Customers of that Company
Delete from Customer where Company=@companyName
End