SQL Server动态查询无效

时间:2017-11-05 02:09:36

标签: sql-server

有人可以帮我处理以下存储过程吗?

执行此存储过程时:

DECLARE @retVal varchar(500)

EXEC utility_getDatabaseLocation 
            @program = "RH17009", @locationOutput = @retVal OUTPUT

SELECT @retVal

它返回以下@sql语句:

SELECT Location 
FROM Intranet.dbo.tbl_Campaigns 
WHERE JobCode = @paramProgram

因此未传递动态SQL语句参数。

ALTER PROCEDURE [dbo].[utility_getDatabaseLocation]
    @program AS NVARCHAR(75),
    @locationOutput VARCHAR(500) OUTPUT
AS
   DECLARE @ParmDefinition nvarchar(500);

   SET @ParmDefinition = N'@paramProgram varchar(75),@paramOUTPUT varchar(500) OUTPUT';

   DECLARE @sql AS nvarchar(500)
   BEGIN
       SET @sql = N'SELECT Location FROM Intranet.dbo.tbl_Campaigns WHERE JobCode = @paramProgram'

       EXEC sp_executesql @sql, @ParmDefinition,  
            N'@paramProgram=@program', N'@paramOUTPUT=@locationOutput OUTPUT'

       PRINT @sql
       PRINT @locationOutput 
   END

1 个答案:

答案 0 :(得分:0)

以下是现在有效的更新代码:

    ALTER PROCEDURE [dbo].[utility_getDatabaseLocation]
    @program as nvarchar(75),
    @locationOutput varchar(250) OUTPUT
AS

BEGIN
    DECLARE @ParmDefinition nvarchar(500);

    DECLARE @sql AS nvarchar(500)

    SET @sql = N'SELECT @paramOUTPUT = MAX(Location) FROM Intranet.dbo.tbl_Campaigns WHERE JobCode= @paramProgram';
    SET @ParmDefinition = N'@paramProgram varchar(75),@paramOUTPUT varchar(250) OUTPUT';

    EXECUTE sp_executesql   @sql,   @ParmDefinition,  @paramProgram=@program, @paramOUTPUT=@locationOutput OUTPUT

END