执行动态创建的查询时出错

时间:2014-09-03 09:49:23

标签: sql-server tsql stored-procedures

My StoredProcedure就像这样

    USE [Workcamps]
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER   PROCEDURE  [dbo].[ph_TshirtReport]

    @CampCode nvarchar(20) = NULL,
    @strAddtlCriteria VARCHAR(150) = ''
AS

    DECLARE @strSQL VARCHAR(900)

    SET @strSQL = 'select distinct [VolID]  ,[VolFName]  FROM [vTShirtBase] WHERE @CampCode IS NULL OR CampCode=@CampCode'

    IF Len(@strAddtlCriteria) > 0
        SET @strSQL = @strSQL + ' and ' + @strAddtlCriteria

    exec (@strSQL)

我正在执行它

    USE [Workcamps]
GO

DECLARE @return_value int

EXEC    @return_value = [dbo].[ph_TshirtReport]
        @CampCode = N'14CA11',
        @strAddtlCriteria = N'GroupStaff = 0 And TSWithGS = 0 And StaffAtTraining = 0 And MinJobType <> S And Setup = 0'

SELECT  'Return Value' = @return_value

GO

一切看起来都不错。但它会引发错误

    Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "@CampCode".

我不知道为什么会发生这种情况,任何人都可以指出我做错了吗?

2 个答案:

答案 0 :(得分:0)

您需要更改SET @strSQL代码。设置如下:

SET @strSQL = 'select distinct [VolID]  ,[VolFName]  FROM [vTShirtBase] WHERE ' + @CampCode + ' IS NULL OR CampCode=' + @CampCode

答案 1 :(得分:0)

检查一下:

ALTER   PROCEDURE [dbo].[ph_TshirtReport]
@CampCode NVARCHAR(20) = NULL ,
@strAddtlCriteria VARCHAR(150) = ''
AS
DECLARE @strSQL VARCHAR(900)


SET @strSQL = 'Declare @CampCode nvarchar(20) ' + CHAR(13)
SET @strSQL = @strSQL + ' Set  @CampCode = ''' + @CampCode + '''' + CHAR(13)
SET @strSQL = @strSQL + ' select distinct [VolID]  ,[VolFName]  FROM [vTShirtBase] WHERE  @CampCode   IS NULL OR CampCode= ''' + @CampCode + ''''

IF LEN(@strAddtlCriteria) > 0
    SET @strSQL = @strSQL + ' and ' + @strAddtlCriteria
PRINT @strSQL
EXEC (@strSQL)