首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

小弟写的存储过程在这儿老是出错

2012-01-19 
求教:小弟写的存储过程在这儿老是出错请看小弟写的存储过程的一部分,建立时总是提示“错误137:必须声明变量

求教:小弟写的存储过程在这儿老是出错
请看小弟写的存储过程的一部分,建立时总是提示“错误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
[解决办法]
表名,字段名是變量,使用動態語句。

一樓的語句會報錯

热点排行