如何在动态sql查询中传递int参数

时间:2013-10-11 12:50:07

标签: sql sql-server stored-procedures

这是我的存储过程:

ALTER PROCEDURE [dbo].[procViewAdvSearchL1]
-- Add the parameters for the stored procedure here
    @keyword nvarchar(800),
    @CourtID    int = null,
    @SYear int = null,
    @EYear int = null

AS
BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[viewTextSearchL]'))
DROP VIEW [dbo].[viewTextSearchL]


Declare @sqlquery nvarchar(1500)
Set @sqlquery ='
CREATE VIEW viewTextSearchL
AS
    SELECT     tblCase.judgement_id AS ID, tblCase.case_number AS Case_No, tblCase.applicant_name AS Aplicant, tblCase.respondent_name AS Respondent, tblCase.case_date AS Case_Date, 
                  tblCourt.court_name AS Court_Name, tblCase.YearOfCase
FROM         tblCase INNER JOIN
                  tblCourt ON tblCase.court_id = tblCourt.court_id INNER JOIN
                  tblJudgement ON tblCase.judgement_id = tblJudgement.judgement_id
WHERE     CONTAINS(tblJudgement.judgement_desc,'+@keyword+') AND (CAST(tblCase.YearOfCase AS int) BETWEEN '+@SYear+' AND  '+@EYear+')' 

EXECUTE(@sqlquery)

END

但是这会给出错误

  

Msg 137,Level 15,State 2,Procedure viewTextSearchL,Line 9
  必须声明标量变量" @ SYear"。

3 个答案:

答案 0 :(得分:1)

根据发布的代码,我只能看到转换错误:

Conversion failed when converting the varchar value '' to data type int.

使用以下

CONVERT(VARCHAR(4),@SYear)

CONVERT(VARCHAR(4),@EYear)

答案 1 :(得分:0)

以下是更正后的查询

SELECT     tblCase.judgement_id AS ID, tblCase.case_number AS Case_No, tblCase.applicant_name AS Aplicant, tblCase.respondent_name AS Respondent, tblCase.case_date AS Case_Date, 
                      tblCourt.court_name AS Court_Name, tblCase.YearOfCase
    FROM         tblCase INNER JOIN
                      tblCourt ON tblCase.court_id = tblCourt.court_id INNER JOIN
                      tblJudgement ON tblCase.judgement_id = tblJudgement.judgement_id
    WHERE     CONTAINS(tblJudgement.judgement_desc,'+@keyword+') AND (tblCase.court_id = '+CONVERT(VARCHAR(4),@CourtID)+')AND (CAST(tblCase.YearOfCase AS int) BETWEEN '+CONVERT(VARCHAR(4),@SYear)+' AND  '+CONVERT(VARCHAR(4),@EYear)+')' 

答案 2 :(得分:-1)

@CourtID    int = null,
@SYear int = null,
@EYear int = null

以上变量应该在NVARCHAR中声明因为动态查询 除了它之外给出错误。

It Should be
@CourtID    NVARCHAR(20) = null,
@SYear NVARCHAR(20) = null,
@EYear NVARCHAR(20) = null

使用exec sp_execute执行查询,EXECUTE(@sqlquery)

除外

有关详细信息click here