I am currently engaged in a project using SQL Server, and I’m seeking guidance on how to fill a table variable with data using the SELECT INTO method. I have a stored procedure that operates correctly with INSERT and OUTPUT, but I am eager to make my code more efficient.
Here’s an example of my current setup:
CREATE PROCEDURE [dbo].[Product_AddProduct]
@ClientId uniqueidentifier,
@ProductDescription nvarchar(100),
@CategoryId int,
@User nvarchar(100)
AS
BEGIN
DECLARE @RelatedCategoryId uniqueidentifier;
SET @RelatedCategoryId =
(
SELECT top(1) CategoryId
FROM Categories
WHERE ClientId = @ClientId
)
DECLARE @ProductTable TABLE
(
ProductId uniqueidentifier,
ClientId uniqueidentifier,
ProductDescription nvarchar(100),
CategoryId int,
User nvarchar(100),
CreatedAt datetime
);
INSERT INTO Product
OUTPUT INSERTED.* INTO @ProductTable
SELECT NEWID(), @ClientId, @ProductDescription, @CategoryId, @User, GETDATE()
END
Now, I wish to achieve something similar to this:
DECLARE @CustomerInfo TABLE
(
CustomerId uniqueidentifier,
FirstName nvarchar(100),
LastName nvarchar(100),
Email nvarchar(100)
);
SELECT
CustomerId,
FirstName,
LastName,
Email
INTO
@CustomerInfo
FROM
Customers
WHERE
CustomerId = @CustomerId
However, I encounter an error when attempting this method. Is it possible to directly populate a table variable without resorting to separate INSERT queries or executing multiple queries on the same table?