1

I am writing a store procedure in T-SQL which inserts a row to the table, based on parameters

@UserName ,@CompanyName ,@RestName,@Desc

INSERT INTO Orders(UserId,CompanyId,RestId)
    SELECT UserNames.Id,CompanyNames.Id,RestNames.Id FROM UserNames,CompanyNames,RestNames
    WHERE
    UserNames.Name = @UserName AND 
    CompanyNames.Name = @CompanyName AND
    RestNames.Name = @RestName

Besides the insert to the 3 columns above,I also want to insert the @Desc value. I tried :

INSERT INTO Orders(UserId,CompanyId,RestId,Desc)
        VALUES(
        (SELECT UserNames.Id,CompanyNames.Id,RestNames.Id FROM UserNames,CompanyNames,RestNames
        WHERE
        UserNames.Name = @UserName AND 
        CompanyNames.Name = @CompanyName AND
        RestNames.Name = @RestName),@Desc)

Only one expression can be specified in the select list when the subquery is not introduced with EXISTSt- It doesn`t work giving the following error:

1 Answer 1

2
@UserName ,@CompanyName ,@RestName,@Desc

INSERT INTO Orders(UserId,CompanyId,RestId, Desc_Column)
SELECT UserNames.Id,CompanyNames.Id,RestNames.Id , @Desc  --<-- Just SELECT that variable
FROM UserNames,CompanyNames,RestNames                        -- in your select statement.
WHERE UserNames.Name = @UserName 
AND CompanyNames.Name = @CompanyName 
AND RestNames.Name = @RestName

Retrieve ID Values Inserted

DECLARE @t TABLE (ID INT);   --<-- Declare a table variable 

INSERT INTO Orders(UserId,CompanyId,RestId, Desc_Column)
OUTPUT Inserted.ID    INTO @t                        --<-- use OUTPUT, get values from INSERTED Table
SELECT UserNames.Id,CompanyNames.Id,RestNames.Id , @Desc  --and insert them into your table variable
FROM UserNames,CompanyNames,RestNames                        
WHERE UserNames.Name = @UserName 
AND CompanyNames.Name = @CompanyName 
AND RestNames.Name = @RestName

/*At last just simply select from that table variable to get the inserted IDs*/
 SELECT * FROM @t
Sign up to request clarification or add additional context in comments.

7 Comments

Otherwise, use [Desc] if that is the column name, as it's a SQL keyword.
@M.Ali - Thank you - it works!How can this query also return a value of a new (inserted ) row?ID
@Yakov do you mean the ID generated by the Identity column ?? or the ID you have just inserted ???
@M.Ali - yes!the ID generated by the Identity column
@M.Ali - I need to return only the ID,of the inserted row
|

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.