将字符串作为带有标识ID的参数传递给存储过程

时间:2016-03-02 08:45:03

标签: sql sql-server tsql stored-procedures

我有一个类似下面的过程,我将一个字符串作为参数传递给它:

CREATE PROCEDURE AddWantedJob
    (@JTID int ,
     @LocationID int,
     @OpeningDate datetime,
     @closingDate datetime,
     @JobDesc nvarchar(max),
     @InputQuery NVARCHAR(500))
AS
BEGIN
    BEGIN TRANSACTION

    DECLARE @JobID AS INT
    DECLARE @QueryString NVARCHAR(2000)

    SET @QueryString = 'insert into WantedJobWorkType (JobID , WTID ) values '
    SET @QueryString = @QueryString + @InputQuery

    INSERT INTO WantedJobs (JTID, LocationID, OpeningDate, closingDate, JobDesc) 
    VALUES (@JTID, @LocationID, @OpeningDate, @closingDate, @JobDesc)

    SET @JobID = SCOPE_IDENTITY()

    EXEC (@QueryString)
    COMMIT TRANSACTION
END

我将(@JobID, 1), (@JobID, 2 )之类的字符串传递给它,但是我收到错误,为什么?

  

Msg 137,Level 15,State 2,Line 1
  必须声明标量变量" @ JobID"。

1 个答案:

答案 0 :(得分:1)

参数化您的动态查询执行

SET @QueryString = 'insert into WantedJobWorkType (JobID , WTID ) values '
SET @QueryString = @QueryString + @InputQuery 

INSERT INTO WantedJobs (JTID , LocationID , OpeningDate ,closingDate , JobDesc ) 
VALUES (@JTID , @LocationID , @OpeningDate ,@closingDate , @JobDesc)
SET @JobID = SCOPE_IDENTITY()

EXEC sp_executesql @QueryString,N'@JobID INT',@JobID = @JobID 

但是你可以在输入字符串而不是(@JobID , 1) , (@JobID , 2)中单独传递1和2。然后拆分值并使用生成的标识值插入它。它将避免动态部分