Umair
Umair

Reputation: 19

Four (4) Sub Queries

Is there any possible way to do this kind of sub query:

DELETE (INSERT (SELECT (INSERT)))

I know how to: INSERT (SELECT):

INSERT INTO r (u_id,role) 
    VALUES ((SELECT u_id FROM USER WHERE email="[email protected]"),'Agent');

My problem is:
User is present in request table when he verifies his account, system must have to:

  1. Create user in user table
  2. Create user role in role table
  3. Delete user from request table

Upvotes: 4

Views: 104

Answers (1)

DavidG
DavidG

Reputation: 119017

The reason you can do INSERT INTO .... SELECT ... is that the SELECT is being used as the input into the INSERT query.

However, an INSERT query doesn't return anything in that way. You are much better off just writing 3 distinct queries like this:

--Create user in user table
INSERT INTO UserTable VALUES (...)

--Create user role in role table
INSERT INTO UserRoles VALUES (...)

--Delete user from request table
DELETE FROM Requests WHERE ...

You could even wrap that all in a transaction to ensure all or none of the queries run:

BEGIN TRAN

--Create user in user table
INSERT INTO UserTable VALUES (...)

--Create user role in role table
INSERT INTO UserRoles VALUES (...)

--Delete user from request table
DELETE FROM Requests WHERE ...

COMMIT

I suspect also that you are wanting to use the ID of the user that you've created. To do this, assuming your UserTable has an IDENTITY column, you can use the SCOPE_IDENTITY function:

BEGIN TRAN

--Create user in user table
INSERT INTO UserTable VALUES (...)

DECLARE @UserID INT
SET @UserID = SCOPE_IDENTITY()

--Create user role in role table
INSERT INTO UserRoles (UserID, RoleID) VALUES (@UserID, ...)

--Delete user from request table
DELETE FROM Requests WHERE ...

COMMIT

Upvotes: 3

Related Questions