I’m new into SQL and stored procedures, and need some help with the stored procedure below. I have to tables that are connected to each other: “User” and “Profile”.
When deleting a user the user profile should also be deleted, and that’s what the SP below does. However, when executing the SP all the UserIDs in the table User shows up (of course because of “SELECT UserID), and this is something I don’t want.
So, I guess my question is how to write the Sp so that it works without using SELECT?
Thanks in advance.
CREATE PROCEDURE usp_DeleteUser
@UserID int
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION;
SELECT u.UserID
FROM [User] AS u INNER JOIN Profile AS p
ON u.UserID = p.UserID;
DELETE FROM Profile
WHERE UserID = @UserID;
DELETE FROM [User]
WHERE UserID = @UserID;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
RAISERROR ('Borttagningen gick inte att genomföra!',16,1)
END CATCH
END
GO
Profile.UserIDshould be a foreign key indicating a one-to-one relationship with theUsertable, withON DELETE CASCADEspecified. Then you delete the record from theUsertable, and the associated record in theProfiletable will automatically be removed.