2014-09-03 38 views
0

我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 [email protected]' 

    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". 

我不知道爲什麼發生這種情況,任何人都可以指出我做錯了什麼?

回答

0

您需要更改您的SET @strSQL代碼。設置這樣的:

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

仍然沒有工作。和同樣的錯誤 – Athul 2014-09-03 10:13:36

+0

@Athul你現在可以嘗試。我沒有注意到變量被使用了兩次 – Jaguar 2014-09-03 10:15:21

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)