2

I'm trying to learn SQL and I've run into a problem with stored procedures. I've got a tables structure like in the picture, where Repair.RepairerId and Repair.CarId are foreign keys for the appropriate tables.

DB structure

What I need to do is to create a stored procedure that allows a user to delete entities from table Repair where user can select the car model and the repairer name in Microsoft SQL Server 2017.

For now I have the next code:

CREATE PROCEDURE [dbo].[DeleteRepairInfo]
    @Name nvarchar(MAX),
    @Model nvarchar(MAX)
AS
    DELETE Repair.*
    FROM Repair INNER JOIN Repairer ON Repair.RepairerId = Repairer.Id
                INNER JOIN Car ON Repair.CarId = Car.Id
    WHERE Car.Model LIKE @Model AND Repairer.Name LIKE @Name
GO

However SQL Editor in Visual Studio 2017 gives me the error:

SQL46010: Incorrect syntax near ..

Also all the INNER JOIN statements and their = signs are greyed out as well as words LIKE, AND, and the final LIKE. (I'm not sure if this is okay).

You can see this on the next picture:

enter image description here

4

2 回答 2

2

你好吗?

我认为问题在于您没有DELETE正确使用

以下示例将对您有所帮助!

CREATE PROCEDURE [dbo].[DeleteRepairInfo]
    @Name nvarchar(MAX),
    @Model nvarchar(MAX)
AS
    DELETE FROM Repair as R
    WHERE R.CarId in (select CarId from Car where Model = @Model) 
    and R.RepairerId in (select RepairerId from Repairer where Name = @Name)        
GO

假设您可以拥有超过 1 辆相同型号的汽车和多个相同名称的维修商!

祝你好运 :)

于 2017-12-28T18:49:18.433 回答
2

我会把逻辑写成:

CREATE PROCEDURE [dbo].[DeleteRepairInfo] (
    @Name nvarchar(MAX),
    @Model nvarchar(MAX)
) AS
BEGIN
    DELETE r
    FROM Repair r INNER JOIN
         Repairer rr
         ON r.RepairerId = rr.Id INNER JOIN
         Car c
         ON r.CarId = c.Id
    WHERE c.Model LIKE @Model AND rr.Name LIKE @Name;
END;  -- DeleteRepairInfo

您的查询的问题是语法Repair.*。那是无效的。注意其他一些事情:

  • 这引入了表别名,因此查询更易于编写和阅读。
  • 存储过程的主体由BEGIN/包围,END因此很容易看到。
  • 用存储过程的END名称进行注释。
  • 参数用括号括起来。

这些都是“可选的”。但是编写清晰的代码是一个学习的好习惯。

于 2017-12-28T18:45:19.363 回答