存储过程包含多个查询和参数。

huangapple go评论57阅读模式
英文:

Stored Procedure with Multiple Queries and Parameters

问题

我正在使用Microsoft SQL Server和Java。

我打算创建一个全局存储过程函数,它将从一个表中复制记录到另一个表中。

我的当前存储过程:

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

当我执行这个存储过程时,我收到以下错误消息:

SQL错误 [102] [S0001]:'@newTable' 附近有语法错误。

替换参数后的示例最终查询:

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

请帮助解决这个问题。

谢谢。

英文:

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.

答案1

得分: 2

以下是代码的翻译部分:

请将存储过程的主体更改如下:

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
英文:

Please change the body of the stored 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

huangapple
  • 本文由 发表于 2023年3月1日 10:49:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75599157.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定