日期:2014-05-18  浏览次数:20352 次

求教:小弟写的存储过程在这儿老是出错
请看小弟写的存储过程的一部分,建立时总是提示“错误137:必须声明变量 '@tblName '”,可是我在开头已经声明了变量@tblName了呀?请问如何解决?


Create   PROCEDURE   Hits_Update
 
@tblName   varchar(20)   =   ' ', --   表名  
 
@strWhere   varchar(200)   =   ' ', --   更新条件   (注意:   不要加   where)

@timeField   varchar(20)   =   ' ' --   时间比较字段    
 
AS    
 
declare   @strSQL   varchar(500)               --   主语句

declare   @nowTime   datetime --   当前时间

declare   @strTime   datetime --   比较时间字段的值

declare   @tempInt   int --   临时变量


set   @nowTime   =   GetDate()

select   @strTime=@timeField   from   @tblName   where   @strWhere
--老是提示这儿“错误137:必须声明变量 '@tblName '”


GO

------解决方案--------------------
要用動態語句

Create PROCEDURE Hits_Update

@tblName varchar(20) = ' ', -- 表名

@strWhere varchar(200) = ' ', -- 更新条件 (注意: 不要加 where)

@timeField varchar(20) = ' ' -- 时间比较字段

AS

declare @strSQL Nvarchar(500) -- 主语句

declare @nowTime datetime -- 当前时间

declare @strTime datetime -- 比较时间字段的值

declare @tempInt int -- 临时变量


set @nowTime = GetDate()

Select @strSQL = 'select @strTime= ' +@timeField + ' from '+ @tblName + ' where '+ @strWhere
EXEC sp_executesql @strSQL, N '@strTime datetime output ', @strTime output
GO
------解决方案--------------------
表名,字段名是變量,使用動態語句。

一樓的語句會報錯