I'm trying to copy data from one table to another and add one column to the target table that isn't present in the source table using INSERT INTO
and a stored procedure to generate the value for the additional column.
The target table has counter
field (integer) that needs to be incremented for every row inserted (it is not an IDENTITY
column, incrementing this counter is handled by other code).
The Counter table has counters for multiple tables and need to pass the Counter Name as a parameter to the stored procedure and use output
as the additional column for the target table.
I have a stored procedure and can pass it a parameter (counter name, in example below counter name is "Counter_123") and it has as output
value as the new counter value.
I can run the stored procedure like this and it works fine:
declare @value int
exec GetCounter 'Counter_123', @value output
PRINT @value
In this case if the counter was 3, the output
is 4.
Here is what I'm trying to do in my INSERT INTO
:
INSERT INTO Target_Table (col1, col2, col3, uspGetCounter 'Counter_123')
SELECT (val1, val2, val3)
FROM Source_Table
WHERE ...
Error returned is syntax error near 'Counter_123'
I've also tried to put the stored procedure in the values list but that doesn't work either.
What is the syntax to call a stored procedure, pass it a parameter, and use the output
in the INSERT INTO
query as a value for a column?
Here is the stored procedure code for reference:
CREATE PROCEDURE [dbo].[uspGetCounter]
@CounterName varchar(30) = '',
@LastValue int OUTPUT
AS
BEGIN
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION
if not exists (select * from Counter where COUNTER_NAME=@CounterName)
insert Counter (COUNTER_NAME, LAST_VALUE)
values (@CounterName,0)
select @LastValue=LAST_VALUE+1
from Counter (holdlock)
where COUNTER_NAME= @CounterName
update Counter
set LAST_VALUE=@LastValue,
LAST_UPDATED=getdate(),
from Counter
where COUNTER_NAME=@CounterName
COMMIT TRANSACTION
END