SQL Server Stored Procedure with Multiple Queries and Parameters

qfe3c7zg  于 2023-03-07  发布在  其他
关注(0)|答案(1)|浏览(131)

I'm using Microsoft SQL Server and Java for this.

I'm intending to create a global procedure function, in which it will copy the records from 1 table to another table.

My current procedure:

create procedure callProcedure(@newTable varchar(100),
@tableField varchar(8000),
@table varchar(100))
as
begin
DELETE FROM @newTable;

SET IDENTITY_INSERT @newTable ON;

INSERT INTO @newTable(@tableField) SELECT @tableField FROM @table

SET IDENTITY_INSERT @newTable OFF;
end

When I execute the procedure. This is the error that I received.

SQL Error [102] [S0001]: Incorrect syntax near '@newTable'.

Sample final queries after being replaced with parameters

EXEC callProcedure(@newTable = 'EMPLOYEE_1', @tableField = 'ID, NAME, STATUS', @table = 'EMPLOYEE')

Please help with this.

Thank you.

EXEC callProcedure(@newTable = 'EMPLOYEE_1', @tableField = 'ID, NAME, STATUS', @table = 'EMPLOYEE')

will return the result.

sqserrrh

sqserrrh1#

Please change the body of the store procedure as follows:

alter procedure callProcedure(@newTable varchar(100),
@tableField varchar(8000),
@table varchar(100))
as
BEGIN
DECLARE @query NVARCHAR(MAX)
 SET @query='DELETE FROM '+@newTable+';';

SET @query+='SET IDENTITY_INSERT '+@newTable+' ON;';

SET @query +='INSERT INTO '+@newTable+'('+@tableField+') SELECT '+@tableField+' FROM '+@table+';';

SET @query+= 'SET IDENTITY_INSERT '+@newTable+' OFF;';
EXEC( @query)
END

相关问题