3

I am using SQL Server 2008 R2 and I want to create a stored procedure that deletes from two tables using a paramater (id).

This is the stored procedure:

CREATE PROCEDURE [dbo].[sp_deleteDecision]
@ID int
AS

DELETE FROM [dbo].[tblDecisionInvolvement] as di
WHERE di.DecisionId = @ID
DELETE FROM [dbo].[tblDecision] as d
WHERE d.Id =@ID

GO

This is the error I get when I try to create it:

Msg 156, Level 15, State 1, Procedure sp_deleteDecision, Line 6
Incorrect syntax near the keyword 'as'.
Msg 156, Level 15, State 1, Procedure sp_deleteDecision, Line 8
Incorrect syntax near the keyword 'as'.

Note that changing the DELETE FROM to

SELECT * FROM 

it works.

Is it even possible to delete something using parameters?

Ty.

3
  • 1
    Problem is alias, use alias only when you use joins... Commented Aug 7, 2012 at 12:48
  • 1
    Where did you see syntax that used AS in a delete this way? Did you look at the official documentation for the DELETE command when you encountered this error? Commented Aug 7, 2012 at 12:48
  • No, I was looking at the stored procedure page. I did not realise that adding aliases was causing the problem. Commented Aug 7, 2012 at 12:57

1 Answer 1

13

You aren't allowed to introduce an alias at that part of a DELETE statement - nor do you need one in this case:

USE ChessDb01
GO
CREATE PROCEDURE [dbo].[sp_deleteDecision]
@ID int

AS

DELETE FROM [dbo].[tblDecisionInvolvement]
WHERE DecisionId = @ID
DELETE FROM [dbo].[tblDecision]
WHERE Id =@ID

GO

For a more complex query, you might want to use an alias, but note that (confusingly), the DELETE will have two FROM clauses - and you can only introduce the alias in the second one:

DELETE FROM di
FROM [dbo].[tblDecisionInvolvement] di
            inner join
      AnotherTable tab
           on
              di.Column = tab.Column2
WHERE tab.Column99 = @Value
Sign up to request clarification or add additional context in comments.

3 Comments

I usually leave out the first FROM in your second example.
Thank you for the fast reply. I removed the aliases and it works now. I feel relieved; thank you!
Aliasing can be used in Delete but it just over complicates it. Example Delete a from Table as a where column=@id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.