Writing a T-SQL stored procedure to receive 4 numbers and insert them into a table
You could also use a table valued parameter type in the stored procedure and pass numbers through this tvp.
Create the type
CREATE TYPE GetNumbers AS TABLE
( Numbers INT );
GO
Create the procedure
CREATE PROCEDURE dbo.InsertNumbers
@GetNumbers GetNumbers READONLY
AS
SET NOCOUNT ON;
CREATE TABLE #Temp(Num int);
INSERT INTO #Temp(Num)
SELECT Numbers
FROM @GetNumbers;
SELECT * FROM #Temp;
DROP TABLE #Temp;
GO
Inserting into temp table is not really needed here, only done to keep it the same as the question.
Fill up a variable with data and call the procedure
/* Declare a variable that references the type. */
DECLARE @GetNumbers AS GetNumbers;
/* Add data to the table variable. */
INSERT INTO @GetNumbers (Numbers)
VALUES(10),(20),(30),(40);
/* Pass the table variable data to a stored procedure. */
EXEC InsertNumbers @GetNumbers;
The example used and more on tvp's here
Declare
@1 Int = 10,
@2 Int = 20,
@3 Int = 30,
@4 Int = 40
Create table #Temp(Num int)
--1st way
INSERT #Temp(Num)
SELECT @1
UNION ALL
SELECT @2
UNION ALL
SELECT @3
UNION ALL
SELECT @4
SELECT * FROM #Temp
TRUNCATE TABLE #Temp
--2nd way
INSERT #Temp(Num)
VALUES
(@1),
(@2),
(@3),
(@4)
SELECT * FROM #Temp
DROP TABLE #Temp
CREATE PROCEDURE dbo.InsertFourValues (@I1 int, @I2 int, @I3 int, @I4 int)
AS
BEGIN
--the table below must already exist
INSERT INTO dbo.MyTable (MyIntColumn)
VALUES (@I1), (@I2), (@I3), (@I4);
END
Now you just call it using your values:
EXEC dbo.InsertFourValues (10, 20, 30, 40);